Joe McHart Joe McHart - 2 months ago 7
Java Question

how to store data in a two dimensional arraylist and display them using double iterator?

There is a problem with the iterator. The program accepts the elements, store it. but upon displaying, it crashes. Why does this happens? And, what is the correct way of displaying the elements?

public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int num;
String dec;
ArrayList<ArrayList<Integer>> al = new ArrayList<ArrayList<Integer>>();

while(true){
ArrayList<Integer> al2 = new ArrayList<Integer>();
while (true){
System.out.print("Enter a number to store in inner arraylist or zero to exit inner arraylist:\t");
num = sc.nextInt();

if (num!=0){
al2.add(num);
}else{
break;
}
}
al.add(al2);
System.out.print("Exit(Y/y):\t");
dec=sc.next();
if(dec.equals("Y") || dec.equals("y")){
Iterator<ArrayList<Integer>> it = al.iterator();
Iterator<Integer> it2 = al2.iterator();
while(it.hasNext()){
while(it2.hasNext()){
System.out.print(it2.next() + " ");
}
System.out.println();
}
break;
}
}

sc.close();

}

Answer

You need to create your inner iterator with each iteration of the outer loop. You can't reuse it since it's tied to the individual array list, and when the outer loop fetches the next iterator, the original it2 is useless. Again, create it within the outer loop. Something like:

if(dec.equals("Y") || dec.equals("y")){
    Iterator<ArrayList<Integer>> it = al.iterator();
    // Iterator<Integer> it2 = al2.iterator();
    while(it.hasNext()){
        ArrayList<Integer> myList = it.next();
        Iterator<Integer> it2 = myList.iterator();
        while(it2.hasNext()){
            System.out.print(it2.next() + " ");
        }
        System.out.println();
    }
    break;
}
Comments