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);
         }
    }
}

Recommended Answers

All 2 Replies

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.

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.