Home > Blockchain >  How do i initialize a 2D Array with m(rows), n(cols) in java?
How do i initialize a 2D Array with m(rows), n(cols) in java?

Time:06-05

I wanted to initialize a 2D arraylist of size 2n-1(rows), n(cols)

    int num = 3; 
    // declare an arrayList of ArrayLists or 2D ArrayList
    ArrayList<ArrayList<Integer>> list =  
           new ArrayList<ArrayList<Integer>>(num);

The above syntax is to create 2D ArrayList of size Num*Num.

In arrays we initialize with M*N, similarly can we do with ArrayLists? if yes, how?

I want syntax to initialize with M*N.

CodePudding user response:

Unlike an Array which must be initialized to a fixed length, an ArrayList can grow dynamically, you don't have to worry about M and N to initialize it. You worry about that when you want to fill the ArrayList and if filling the collection to M and N is your specific requirement then do so after the ArrayList has been declared. So, ArrayList<ArrayList<Integer>> list = new ArrayList<>(); is all you need.

There are a number of ways to fill the ArrayLists to your desired M (rows) and N (columns). Here is a relatively decent visual way to do it.

ArrayList<ArrayList<Integer>> list = new ArrayList<>();
ArrayList<Integer> innerList;
int m = 20;  // Rows
int n = 10;  // Columns 
int incrementer = 1;

for (int i = 0; i < m; i  ) {
    innerList = new ArrayList<>();
    for (int j = 0; j < n; j  ) {
        innerList.add(j   incrementer);
    }
    list.add(innerList);
    incrementer   ;
}
    
// Now to display (print) the 2D ArrayList into the Console Window:
for (ArrayList<Integer> inner : list) {
    for (Integer ints : inner) {
        System.out.printf("%-3s ", ints);
    } 
    System.out.println();
}

The console should display:

1   2   3   4   5   6   7   8   9   10  
2   3   4   5   6   7   8   9   10  11  
3   4   5   6   7   8   9   10  11  12  
4   5   6   7   8   9   10  11  12  13  
5   6   7   8   9   10  11  12  13  14  
6   7   8   9   10  11  12  13  14  15  
7   8   9   10  11  12  13  14  15  16  
8   9   10  11  12  13  14  15  16  17  
9   10  11  12  13  14  15  16  17  18  
10  11  12  13  14  15  16  17  18  19  
11  12  13  14  15  16  17  18  19  20  
12  13  14  15  16  17  18  19  20  21  
13  14  15  16  17  18  19  20  21  22  
14  15  16  17  18  19  20  21  22  23  
15  16  17  18  19  20  21  22  23  24  
16  17  18  19  20  21  22  23  24  25  
17  18  19  20  21  22  23  24  25  26  
18  19  20  21  22  23  24  25  26  27  
19  20  21  22  23  24  25  26  27  28  
20  21  22  23  24  25  26  27  28  29  
  • Related