我有以下代码:
public static void printCollection(ArrayList<Data> al, LinkedList<Data> ll, Stack<Data> stack){
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
Data x = (Data)iter.next();
x.print();
}
System.out.println();
}
public static void main(String[] args){
Data x = new Data("Fred", 41);
x.print();
//ArrayList
ArrayList<Data> arrayList = new ArrayList<Data>();
//LinkedList
LinkedList<Data> linkedList = new LinkedList<Data>();
//Stack
Stack<Data> stack = new Stack<Data>();
//'people' variables
Data person1 = new Data("Fred", 21);
Data person2 = new Data("Jane", 21);
Data person3 = new Data("Zoe", 23);
Data person4 = new Data("Harry", 78);
//ArrayList
arrayList.add(person1);
arrayList.add(person2);
arrayList.add(person3);
arrayList.add(2, person4);
printCollection(arrayList, null, null);
//LinkedList
linkedList.add(person1);
linkedList.add(person2);
linkedList.add(person3);
linkedList.add(2, person4);
printCollection(null, linkedList, null);
//Stack
stack.push(person1);
stack.push(person2);
stack.push(person3);
stack.push(person4);
while(stack.isEmpty() == false)
{
stack.pop().print();
}
System.out.println(stack.size());
}
...这会产生 NullPointerException 错误。但是,如果我删除一些代码行以使其看起来像这样:
public static void printCollection(ArrayList<Data> al, LinkedList<Data> ll, Stack<Data> stack){
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
Data x = (Data)iter.next();
x.print();
}
System.out.println();
}
public static void main(String[] args){
Data x = new Data("Fred", 41);
x.print();
//ArrayList
ArrayList<Data> arrayList = new ArrayList<Data>();
//LinkedList
LinkedList<Data> linkedList = new LinkedList<Data>();
//Stack
Stack<Data> stack = new Stack<Data>();
//'people' variables
Data person1 = new Data("Fred", 21);
Data person2 = new Data("Jane", 21);
Data person3 = new Data("Zoe", 23);
Data person4 = new Data("Harry", 78);
//ArrayList
arrayList.add(person1);
arrayList.add(person2);
arrayList.add(person3);
arrayList.add(2, person4);
printCollection(arrayList, null, null);
}
}
...然后就可以正常运行了。我已经检查了多次,但无法检测到错误(没有双关语意图(NullPointerException))。
错误不断出现在以下行:
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
//remaining code omitted for illustration purposes
我不知道它可能是什么,需要一些新的眼光来帮助我看看。
感谢您花时间阅读本文。
米克
最佳答案
在第一种情况下,您为正在使用的唯一集合传递 null
:al
,当您请求迭代器时,它当然会抛出 NPE 。第二种情况不会发生这种情况。
另一个注意事项:您不需要强制转换 iter.next()
调用。
要解决此问题,您可能需要将 printCollection
的签名更改为:
public static void printCollection(Collection<Data> c){
for(Iterator<Data> iter = c.iterator(); iter.hasNext();) iter.next().print();
System.out.println();
}
因为(1)该方法发生了什么,(2)更好地反射(reflect)了命名。编译器将强制您进行一些清理,正确地执行此操作将消除问题或使问题所在变得更加明显。
关于Java ArrayList、LinkedList 和 Stack 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5172815/