[英]Java ArrayList, LinkedList & Stack problem
我有以下代码:
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
的签名printCollection
为:
public static void printCollection(Collection<Data> c){
for(Iterator<Data> iter = c.iterator(); iter.hasNext();) iter.next().print();
System.out.println();
}
因为那是(1)方法的作用,而(2)更好地反映了命名。 编译器将迫使您进行一些清理,正确执行此操作将消除问题或使问题更加明显。
有一次您打电话给:
printCollection(null, linkedList, null);
并查看您的方法的声明。 它尝试从第一个参数获取迭代器。 这导致您的NPE。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.