I have the following code:
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());
}
...which produces a NullPointerException error. However, if I remove some lines of code to make it look like this:
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);
}
}
...then it runs just fine. I have checked multiple times and have been unable to detect the error (no pun intended (NullPointerException)).
The error keeps appearing on the following line:
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
//remaining code omitted for illustration purposes
I have no idea what it could be and need some fresh eyes to help me and take a look.
Thank you for taking the time to read this.
Mick