0

how to store 2d array in arraylist?
and how to print arraylist?

import java.util.ArrayList;

public class aaa {
    public static void main(String[]args)
    {
         ArrayList<Integer[][]> aa= new ArrayList();  ???????????? 
         int bb[][] = {   {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
                            {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} };

         for(int y = 0; y < bb.length; y++) //rows
               {
              for(int x = 0; x < bb[y].length; x++) //cols
                    {
                        aa.add(x,y);
                    }
                }


         for(int i = 0; i < aa.size(); i++)
         {
            System.out.println(aa);
         }
    }
}

Edited by game06

3
Contributors
2
Replies
40
Views
4 Years
Discussion Span
Last Post by stultuske
0

Unless you want to deal with a fixed span for the second dimension, use an ArrayList of ArrayLists.

Also, don't ever use 'aa', 'bb', 'aaa' for names of anything. Name your classes and variables with descriptive, meaningful names and it will be much easier for you and anyone else reading the code to follow your logic.

Edited by Ezzaral

0

also: x and y are ints (primitives, not wrapper objects), they're not two dimensional arrays of Integer objects, which is what you try to store in your arraylist.

ArrayList<Integer[][]> aa= new ArrayList();

this will not compile. if you apply generics to the left side, you must also apply it on the right, like this:

ArrayList<Integer[][]> aa= new ArrayList<Integer[][]>();

aa.add(x,y);

as said before, this makes no sense with the generics you've set on the arraylist. neither x nor y is a valid element. what youcould save in there is the bb array, if you change the type to Integer[][], that is

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.