我的理解是,我的这个要求不可能以直接的方式进行。但我想找到一个可行的解决方案。
这是我如何获得 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++);
}
};