Create multiple arrays

How do you create, say, 30 arrays (no matter what type, say, char [])? It seems to me that it is not a good idea to create them one by one manually. I want to do this using the for loop, but how should I specify identifiers?

+3
source share
3 answers

I recommend reading the array tutorial . It covers basic manipulations with arrays, including the creation of "multidimensional" arrays.

char[][] arr = new char[30][100];

Now you have arr[0], arr[1]..., arr[29]each of which is an array of 100 char.


This snippet shows an example of array initialization and access to them:

  int[][] m = {
     { 1, 2, 3 },
     { 4, 5, 6, 7, 8 },
     { 9 }
  };
  System.out.println(m[1][3]); // prints "7"

  m[2] = new int[] { -1, -2, -3 };
  System.out.println(m[2][1]); // prints "-2";

, Java ; m - . , ( "" ) .


java.util.Arrays. ( , , , ..).

  import java.util.Arrays;

  // ...

  int[][] table = new int[3][];
  for (int i = 0; i < table.length; i++) {
      table[i] = new int[i + 1];
      for (int j = 0; j < table[i].length; j++) {
          table[i][j] = (i * 10) + j;
      }
  }
  System.out.println(Arrays.deepToString(table));
  // prints "[[0], [10, 11], [20, 21, 22]]"
+7

:

char[][] arr = new char[30][];
for (int i=0; i<30; i++) {
  arr[i] = new char[50];
}
+2

I think the easiest way to do this is to use an ArrayList

you can place as many elements in it as you want:

java.util.ArrayList<char[]> array = new java.util.ArrayList<char[]>();
//set
for(int i=0;i<100;i++){
   array.add(new char[]{'a','b''c'});
}
//get
for(int i=0;i<array.size();i++){
   System.out.println(new String(array.get(i)));
}
0
source

Source: https://habr.com/ru/post/1737794/


All Articles