这个问题的解决方法是直截了当的,而且幸运的是你必须实现一次。
import java.util.*;
import org.w3c.dom.*;
public final class XmlUtil {
private XmlUtil(){}
public static List asList(NodeList n) {
return n.getLength()==0?
Collections.emptyList(): new NodeListWrapper(n);
}
static final class NodeListWrapper extends AbstractList
implements RandomAccess {
private final NodeList list;
NodeListWrapper(NodeList l) {
list=l;
}
public Node get(int index) {
return list.item(index);
}
public int size() {
return list.getLength();
}
}
}
一旦将此实用程序类添加到项目中,并将XmlUtil.asList方法的静态导入添加到源代码中,可以使用它:
for(Node n: asList(dom.getElementsByTagName("year"))) {
…
}