Java: How to create a loop that creates arrays?

I need a large series of arrays, right now I'm creating them manually:

int[] row1 = new int[3];
int[] row2 = new int[3];
int[] row3 = new int[3];

      

I would like to create them in an array, something like this:

public final int SIZE = 3;
for (int i = 1;i <= 3;i++)  
  int[] row[i] = new int[3];

      

But I'm not sure how to create arrays in a loop.

How to do it?

Specifically, how can I generate dynamic IDs on each iteration?

+3


source to share


5 answers


Specifically, how can I generate dynamic IDs on each iteration?

Not. Instead, you realize that you actually have a collection of arrays. For example, you could:

int[][] rows = new int[3][3];

      



Or:

List<int[]> rows = new ArrayList<>();
for (int i = 0; i < 3; i++) {
    rows.add(new int[3]);
}

      

+13


source


Arrays always start at index 0

, so it for (int i = 1;i <= 3;i++)

is wrong twice. Once for 1

and once for use SIZE

. You make a multidimensional array like

public final int SIZE = 3;  
int[][] tables = new int[SIZE][SIZE];

      

Note that each value is tables

equal 0

. You can use Arrays.fill(int[],int)

to give each element a single value,

Arrays.fill(tables, 1);
// [[1, 1, 1], [1, 1, 1], [1, 1, 1]]

      



Or you can use a couple of chains for

like

for (int i = 0; i < tables.length; i++) {
  for (int j = 0; j < tables[i].length; j++) {
    tables[i][j] = (tables[i].length * i) + j;
  }
}
// [[0, 1, 2], [3, 4, 5], [6, 7, 8]]

      

And you can use literal assignment as well and you can use Arrays.deepToString(Object[])

to display your multidimensional arrays like

int[][] tables = { { 8, 7, 6 }, { 5, 4, 3 }, { 2, 1, 0 } };
// [[8, 7, 6], [5, 4, 3], [2, 1, 0]]
System.out.println(Arrays.deepToString(tables));

      

+2


source


Just make a 2D array. Follow these steps: -

public final int SIZE = 3;
int row[3][SIZE] = new int[3][SIZE];

      

+1


source


You can use array of arrays here, two dimensional array.

public final int SIZE = 3;
int[][] array = new int[SIZE][SIZE];

      

This way you don't need dymanic ids, you can just use the index. You can access a single item like this:

// i is the index of the array, j is the index of the element
int element = array[i][j];

      

+1


source


Based on your specific request for arrays, you may not be interested in more bloated types. But if that's not a problem, you can use the card. And put each array in a map with a unique ID as a key.

Map myRows = new HashMap <String, int[]>();
myRows.put("row1", new int[] {1,2,3});

      

note: you can easily replace the String key with the Integer key.

+1


source







All Articles