1

我的理解是,我的这个要求不可能以直接的方式进行。但我想找到一个可行的解决方案。

这是我如何获得 Iterable forNamedNodeMap(javax package);

private static Iterable<Node> iterableNamedNodeMap(NamedNodeMap namedNodeMap) {
        return () -> new Iterator<Node>() {

            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < namedNodeMap.getLength();
            }

            @Override
            public Node next() {
                if (!hasNext())
                    throw new NoSuchElementException();
                return namedNodeMap.item(index++);
            }
        };
}

这是可迭代的NodeList(javax)

 private static Iterable<Node> iterableNamedNodeMap(NodeList nodeList) {
            return () -> new Iterator<Node>() {

                private int index = 0;

                @Override
                public boolean hasNext() {
                    return index < nodeList.getLength();
                }

                @Override
                public Node next() {
                    if (!hasNext())
                        throw new NoSuchElementException();
                    return nodeList.item(index++);
                }
            };
    }

由于除了参数之外它们几乎相同,所以我希望有这样的东西,这当然是不对的。NodeList 和 NamedNodeMap 都没有实现通用接口。那么在这里最好的方法是什么。

private static <T extends NodeList | NamedNodeMap> Iterable<Node> iterableNamedNodeMap(T in) {
        return () -> new Iterator<Node>() {

            private int index = 0;

            @Override
            public boolean hasNext() {
                return index < in.getLength();
            }

            @Override
            public Node next() {
                if (!hasNext())
                    throw new NoSuchElementException();
                return in.item(index++);
            }
        };
4

1 回答 1

1

您可以通过创建一个接受两个功能接口(取自NodeListNamedNodeMap使用方法引用)的工厂方法来减少一些样板:

private static Iterable<Node> iterableNodes(
    Supplier<int> lengthGetter,
    Function<int, Node> itemGetter
) {
     return () -> new Iterator<Node>() {
        private int index = 0;

        @Override
        public boolean hasNext() {
            return index < lengthGetter.get();
        }

        @Override
        public Node next() {
            if (!hasNext())
                throw new NoSuchElementException();
            return itemGetter.apply(index++);
        }
    };
}

private static Iterable<Node> iterableNamedNodeMap(NamedNodeMap namedNodeMap) {
    return iterableNodes(namedNodeMap::getLength, namedNodeMap::item);
}

private static Iterable<Node> iterableNodeList(NodeList nodeList) {
    return iterableNodes(nodeList::getLength, nodeList::item);
}
于 2019-06-18T01:14:42.963 回答