0

I am reading Arrays in Java. I want to dynamically create a 2D array in java. I know I've to use Arraylist but I don't know how to actually write the elements to location.

I come from C language background. It is quite easy to create a dynamic array and add elements to it using for loop. However, the same logic didn't work here. I've read another answers but they are not helpful, they're using either using advanced concepts or using static declaration.

ArrayList<Integer> Arr1=new ArrayList<>();
        ArrayList<ArrayList<Integer>> Arr2=new ArrayList<ArrayList<Integer>>();
        for(int i=0;i<rows;i++){
            for(int j=0;j<columns;j++){
                Arr1.add(j);
            }
            Arr2.add(Arr1);
        }

My implementation is wrong but that is the closest I can think about writing elements to a dynamic 2D array in java.

Can someone please help me in understanding how to write elements to a specific row and to a specific column

  • that is an [arraylist](http://stackoverflow.com/questions/2697182/how-to-use-an-array-list) not a primitive array.. secondly if you are using arraylist, you should create new Arr1 within the first for loop..else you are just appending to the old row you set. – Suraj Rao Apr 27 '17 at 04:51

3 Answers3

0

You need to re-initialize Arr1 for every new row. Something like this:

    int rows = 3, columns = 4;
    ArrayList<Integer> Arr1;
    ArrayList<ArrayList<Integer>> Arr2 = new ArrayList<>();
    for (int i = 0; i < rows; i++) {
        Arr1 = new ArrayList<>();
        for (int j = 0; j < columns; j++) {
            Arr1.add(j);
        }
        Arr2.add(Arr1);
    }
    System.out.println(Arr2);

Which should out:

[[0, 1, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]

jrook
  • 3,459
  • 1
  • 16
  • 33
0

You can use below code

   ArrayList<ArrayList<Integer>> Arr2=new ArrayList<ArrayList<Integer>>();
for(int i=0;i<rows;i++){
    ArrayList<Integer> Arr1=new ArrayList<>();
    for(int j=0;j<columns;j++){
        Arr1.add(j);
    }
    Arr2.add(Arr1);
}
Poorvi Nigotiya
  • 438
  • 1
  • 4
  • 16
0

how about this?

ArrayList<ArrayList<Integer>> Arr1=new ArrayList<ArrayList<Integer>>();

for(int i=0;i<rows;i++){
    ArrayList<Integer> Arr2=new ArrayList<Integer>();
    for(int j=0;j<columns;j++){
        Arr2.add(j);
    }
    Arr1.add(Arr2);
}
Anis Jonischkeit
  • 914
  • 7
  • 15