Java中的数组使用

xiaoxiao2026-03-26  3

1.  创造数组(Creating an array)   对于基本数据类型(int, float, char):   int carrot [];                    //不要在[ ]中加数字 carrot = new int [256];   这等价于 int carrot [] = new int [256];   这之后, 我们就可以给数组中的元素赋值, 例如 carrot[5] = 42;   但是对于引用类型, 创造数组之后, 我么只得到一个引用数组, 所以我们必须先要使每个引用指向一个对象(object), 这又叫作 instantiate the elements in array. 例如:   Fruit carrot [] = new Fruit  [256]; for (int i = 0; i < carrot.length; i++) {      carrot[i] = new Fruit();  //通过构造函数, 使reference }                                      //指向对象   2. 初始化数组(initializing an array)     初始化同时, 数组的长度将会被自动指定.   int b[ ] = new int [ ] {1, 2, 2, 3, 5}; Fruit apple[ ] = new Fruit [ ] {new Fruit(), new Fruit(4, 3), null};   3. 数组的数组(arrays of arrays of ...) Java中只存在数组的数组(arrays of arrays), 不存在多维数组(multidimensional arrays).   创造: Fruit apple [ ] [ ]; apple = new Fruit [15] [6]; apply[i] = new Fruit [17]; apply[i][j] = new Fruit();   初始化: int a [][] = new int [][]{                                   {0},                                     {0, 1}                                  }   int a [][] = new int [2][ ]; a[0] = new int [] {0};     // a[0].length equals to 1 a[1] =  new int[] {0, 1}; // a[1].length equals to 2   这里显示出了Java里面包括的是数组的数组, 而不是多维数组. 因为处于低维的各个数组是独立的, 可以具有不同的length.
转载请注明原文地址: https://www.6miu.com/read-5046268.html

最新回复(0)