开发者

Creating lots of arrays

How do you create, say, 30 arrays (it doesn't matter of what type, say, char[])? It seems to me that it is not a good idea, to create them one by one by hand. I want to do that using a "for" cycle, but how should I specify identifiers开发者_如何学Python?


I recommend reading the tutorial on arrays. It covers basic array manipulation, including 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 how to access 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";

This also shows that Java doesn't have true multidimensional arrays; m is really an array of arrays. This means that they can have different lengths ("jagged" arrays), and can be manipulated independently of each other.


You should also familiarize yourself with java.util.Arrays. It provides utility methods for basic array manipulation (converting to string, copying, sorting, binary search, etc).

  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]]"


You can always create arrays of arrays:

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


I think the easiest way to do it is using an ArrayList

you can put as many items as you want in it:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜