如何在Java中声明和初始化数组?

bes*_*nce 1946 java arrays

如何在Java中声明和初始化数组?

glm*_*ndr 2566

您可以使用数组声明或数组文字(但只有在声明并立即影响变量时,才能使用数组文字重新分配数组).

对于原始类型:

int[] myIntArray = new int[3];
int[] myIntArray = {1, 2, 3};
int[] myIntArray = new int[]{1, 2, 3};
Run Code Online (Sandbox Code Playgroud)

例如,对于类,String它是相同的:

String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};
Run Code Online (Sandbox Code Playgroud)

当您首先声明数组然后初始化它时,第三种初始化方法很有用.演员是必要的.

String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};
Run Code Online (Sandbox Code Playgroud)

  • @iamcreasy看起来第二种方式不适用于return语句.`return {1,2,3}`给出错误,而`return new int [] {1,2,3}`工作正常(当然假设你的函数返回一个整数数组). (117认同)
  • 同时采用第二种和第三种方式的目的是什么? (31认同)
  • @iamcreasy我最近编写了一个返回一组int的函数.如果函数内部发生错误,我希望它返回一个特定的值,但返回一个数组所需的函数.哪种方式适用于单行返回语句?只有第三个. (5认同)
  • @apadana在第二种情况下,您将创建一个匿名对象,该对象仅在封闭范围(函数或其他)中定义.将其返回给调用者后,它将不再有效.使用new关键字从堆中分配新对象,它在定义范围之外有效. (4认同)

小智 263

有两种类型的数组.

一维数组

默认值的语法:

int[] num = new int[5];
Run Code Online (Sandbox Code Playgroud)

或者(不太喜欢)

int num[] = new int[5];
Run Code Online (Sandbox Code Playgroud)

给定值的语法(变量/字段初始化):

int[] num = {1,2,3,4,5};
Run Code Online (Sandbox Code Playgroud)

或者(不太喜欢)

int num[] = {1, 2, 3, 4, 5};
Run Code Online (Sandbox Code Playgroud)

注意:为了方便int [] num更可取,因为它清楚地告诉你这里是关于数组的.否则没什么区别.一点也不.

多维数组

宣言

int[][] num = new int[5][2];
Run Code Online (Sandbox Code Playgroud)

要么

int num[][] = new int[5][2];
Run Code Online (Sandbox Code Playgroud)

要么

int[] num[] = new int[5][2];
Run Code Online (Sandbox Code Playgroud)

初始化

 num[0][0]=1;
 num[0][1]=2;
 num[1][0]=1;
 num[1][1]=2;
 num[2][0]=1;
 num[2][1]=2;
 num[3][0]=1;
 num[3][1]=2;
 num[4][0]=1;
 num[4][1]=2;
Run Code Online (Sandbox Code Playgroud)

要么

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };
Run Code Online (Sandbox Code Playgroud)

衣衫褴褛的阵列(或非矩形阵列)

 int[][] num = new int[5][];
 num[0] = new int[1];
 num[1] = new int[5];
 num[2] = new int[2];
 num[3] = new int[3];
Run Code Online (Sandbox Code Playgroud)

所以我们在这里明确定义列.
其他方式:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };
Run Code Online (Sandbox Code Playgroud)

用于访问:

for (int i=0; i<(num.length); i++ ) {
    for (int j=0;j<num[i].length;j++)
        System.out.println(num[i][j]);
}
Run Code Online (Sandbox Code Playgroud)

或者:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}
Run Code Online (Sandbox Code Playgroud)

Ragged数组是多维数组.
有关解释,请参阅官方java教程中的多维数组详细信息

  • 我可能会与您争论多维数组是一种不同“类型”的数组。它只是一个术语,用于描述恰好包含其他数组的数组。外部数组和内部数组(以及中间的数组,如果存在)都只是常规数组。 (3认同)

Nat*_*ate 123

Type[] variableName = new Type[capacity];

Type[] variableName = {comma-delimited values};



Type variableName[] = new Type[capacity]; 

Type variableName[] = {comma-delimited values};
Run Code Online (Sandbox Code Playgroud)

也是有效的,但我更喜欢类型之后的括号,因为更容易看到变量的类型实际上是一个数组.

  • 我同意这一点.变量的类型不是"TYPE",而是实际上是TYPE [],因此以这种方式为我编写它是有意义的. (22认同)
  • 注意`int [] a,b;`将不会与`int a [],b;`相同,如果你使用后一种形式,这是一个容易犯的错误. (11认同)
  • [Google风格](http://google-styleguide.googlecode.com/svn/trunk/javaguide.html#s4.8.3.2-array-declarations)也提出了这一建议. (3认同)

Ani*_*udh 37

您可以通过多种方式在Java中声明数组:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};
Run Code Online (Sandbox Code Playgroud)

您可以在Sun教程站点和JavaDoc中找到更多信息.


小智 28

以下显示了数组的声明,但未初始化该数组:

 int[] myIntArray = new int[3];
Run Code Online (Sandbox Code Playgroud)

以下显示了数组的声明和初始化:

int[] myIntArray = {1,2,3};
Run Code Online (Sandbox Code Playgroud)

现在,以下还显示了数组的声明和初始化:

int[] myIntArray = new int[]{1,2,3};
Run Code Online (Sandbox Code Playgroud)

但是第三个显示了匿名数组对象创建的属性,它由引用变量"myIntArray"指向,所以如果我们只编写"new int [] {1,2,3};" 那么这就是如何创建匿名数组对象.

如果我们只写:

int[] myIntArray;
Run Code Online (Sandbox Code Playgroud)

这不是数组的声明,但以下语句使上述声明完成:

myIntArray=new int[3];
Run Code Online (Sandbox Code Playgroud)

  • 此外,第一个片段*执行*初始化数组 - 保证每个数组元素的值为0. (3认同)
  • 第二种方法和第三种方法之间绝对没有区别,除了第二种方法*仅*在您同时声明变量时才起作用.目前还不清楚"显示匿名数组对象创建的属性"是什么意思,但它们实际上是等效的代码片段. (2认同)

Che*_*het 27

如果您了解每个部分我觉得很有帮助:

Type[] name = new Type[5];
Run Code Online (Sandbox Code Playgroud)

Type[]是名为name 的变量类型("name"称为标识符).文字"Type"是基本类型,括号表示这是该基数的数组类型.数组类型依次​​是它们自己的类型,它允许您创建多维数组(类型为Type []).该关键字表示为新阵列分配内存.括号之间的数字表示新数组的大小和分配的内存量.例如,如果Java知道基类型需要32个字节,并且您需要大小为5的数组,则需要在内部分配32*5 = 160个字节.Type[][]newType

您还可以使用已存在的值创建数组,例如

int[] name = {1, 2, 3, 4, 5};
Run Code Online (Sandbox Code Playgroud)

它不仅会创建空白空间,还会使用这些值填充它.Java可以告诉原语是整数,并且它们中有5个,因此可以隐式确定数组的大小.


Tho*_*ens 25

或者,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];
Run Code Online (Sandbox Code Playgroud)

这声明了一个名为arrayName10 的数组(你要使用0到9的元素).

  • 使用的标准是什么?我刚刚发现了前者,我发现它具有可怕的误导性:| (7认同)
  • 值得我的教授说,第二种方式在Java中更为典型,它更好地传达了正在发生的事情; 作为与变量转换为类型相关的数组. (2认同)
  • 旁注:一种语言具有多个语义,用于声明一个意味着糟糕语言设计的东西. (2认同)

Dav*_*ave 25

此外,如果您想要更动态的东西,还有List接口.这不会表现得那么好,但更灵活:

List<String> listOfString = new ArrayList<String>();

listOfString.add("foo");
listOfString.add("bar");

String value = listOfString.get(0);
assertEquals( value, "foo" );
Run Code Online (Sandbox Code Playgroud)

  • 您创建的列表中调用的"<>"是什么? (2认同)

小智 14

制作数组有两种主要方法:

这一个,对于一个空数组:

int[] array = new int[n]; // "n" being the number of spaces to allocate in the array
Run Code Online (Sandbox Code Playgroud)

而这一个,对于一个初始化的数组:

int[] array = {1,2,3,4 ...};
Run Code Online (Sandbox Code Playgroud)

您还可以创建多维数组,如下所示:

int[][] array2d = new int[x][y]; // "x" and "y" specify the dimensions
int[][] array2d = { {1,2,3 ...}, {4,5,6 ...} ...};
Run Code Online (Sandbox Code Playgroud)


Hyp*_*ino 10

以原始类型int为例.声明和int数组有几种方法:

int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};
Run Code Online (Sandbox Code Playgroud)

在所有这些中,您可以使用int i[]而不是int[] i.

通过反射,您可以使用 (Type[]) Array.newInstance(Type.class, capacity);

请注意,在方法参数中,...表示variable arguments.基本上,任何数量的参数都可以.使用代码更容易解​​释:

public static void varargs(int fixed1, String fixed2, int... varargs) {...}
...
varargs(0, "", 100); // fixed1 = 0, fixed2 = "", varargs = {100}
varargs(0, "", 100, 200); // fixed1 = 0, fixed2 = "", varargs = {100, 200};
Run Code Online (Sandbox Code Playgroud)

在方法内部,varargs被视为正常int[].Type...只能在方法参数中使用,所以int... i = new int[] {}不会编译.

请注意,在传递int[]给方法(或任何其他方法Type[])时,您不能使用第三种方式.在语句中int[] i = *{a, b, c, d, etc}*,编译器假定{...}意味着一个int[].但那是因为你要声明一个变量.将数组传递给方法时,声明必须为new Type[capacity]new Type[] {...}.

多维数组

多维数组很难处理.实质上,2D数组是一个数组数组.int[][]表示一个int[]s 数组.关键是如果a int[][]被声明为int[x][y],则最大索引为i[x-1][y-1].基本上,矩形int[3][5]是:

[0, 0] [1, 0] [2, 0]
[0, 1] [1, 1] [2, 1]
[0, 2] [1, 2] [2, 2]
[0, 3] [1, 3] [2, 3]
[0, 4] [1, 4] [2, 4]
Run Code Online (Sandbox Code Playgroud)


Dmi*_*ets 10

宣言

一维数组

int[] nums1; // best practice
int []nums2;
int nums3[];
Run Code Online (Sandbox Code Playgroud)

多维数组

int[][] nums1; // best practice
int [][]nums2;
int[] []nums3;
int[] nums4[];
int nums5[][];
Run Code Online (Sandbox Code Playgroud)

声明和初始化

一维数组

使用默认值

int[] nums = new int[3]; // [0, 0, 0]

Object[] objects = new Object[3]; // [null, null, null]
Run Code Online (Sandbox Code Playgroud)

使用数组文字

int[] nums1 = {1, 2, 3};
int[] nums2 = new int[]{1, 2, 3};

Object[] objects1 = {new Object(), new Object(), new Object()};
Object[] objects2 = new Object[]{new Object(), new Object(), new Object()};
Run Code Online (Sandbox Code Playgroud)

带循环for

int[] nums = new int[3];
for (int i = 0; i < nums.length; i++) {
    nums[i] = i; // can contain any YOUR filling strategy
}

Object[] objects = new Object[3];
for (int i = 0; i < objects.length; i++) {
    objects[i] = new Object(); // can contain any YOUR filling strategy
}
Run Code Online (Sandbox Code Playgroud)

带循环forRandom

int[] nums = new int[10];
Random random = new Random();
for (int i = 0; i < nums.length; i++) {
    nums[i] = random.nextInt(10); // random int from 0 to 9
}
Run Code Online (Sandbox Code Playgroud)

使用Stream(自 Java 8 起)

int[] nums1 = IntStream.range(0, 3)
                       .toArray(); // [0, 1, 2]
int[] nums2 = IntStream.rangeClosed(0, 3)
                       .toArray(); // [0, 1, 2, 3]
int[] nums3 = IntStream.of(10, 11, 12, 13)
                       .toArray(); // [10, 11, 12, 13]
int[] nums4 = IntStream.of(12, 11, 13, 10)
                       .sorted()
                       .toArray(); // [10, 11, 12, 13]
int[] nums5 = IntStream.iterate(0, x -> x <= 3, x -> x + 1)
                       .toArray(); // [0, 1, 2, 3]
int[] nums6 = IntStream.iterate(0, x -> x + 1)
                       .takeWhile(x -> x < 3)
                       .toArray(); // [0, 1, 2]

int size = 3;
Object[] objects1 = IntStream.range(0, size)
        .mapToObj(i -> new Object()) // can contain any YOUR filling strategy
        .toArray(Object[]::new);

Object[] objects2 = Stream.generate(() -> new Object()) // can contain any YOUR filling strategy
        .limit(size)
        .toArray(Object[]::new);
Run Code Online (Sandbox Code Playgroud)

使用Randomand Stream(自 Java 8 起)

int size = 3;
int randomNumberOrigin = -10;
int randomNumberBound = 10
int[] nums = new Random().ints(size, randomNumberOrigin, randomNumberBound).toArray();
Run Code Online (Sandbox Code Playgroud)

多维数组

使用默认值

int[][] nums = new int[3][3]; // [[0, 0, 0], [0, 0, 0], [0, 0, 0]]

Object[][] objects = new Object[3][3]; // [[null, null, null], [null, null, null], [null, null, null]]
Run Code Online (Sandbox Code Playgroud)

使用数组文字

int[][] nums1 = {
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};
int[][] nums2 = new int[][]{
        {1, 2, 3},
        {4, 5, 6},
        {7, 8, 9}
};

Object[][] objects1 = {
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};
Object[][] objects2 = new Object[][]{
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()},
        {new Object(), new Object(), new Object()}
};
Run Code Online (Sandbox Code Playgroud)

带循环for

int[][] nums = new int[3][3];
for (int i = 0; i < nums.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        nums[i][j] = i + j; // can contain any YOUR filling strategy
    }
}

Object[][] objects = new Object[3][3];
for (int i = 0; i < objects.length; i++) {
    for (int j = 0; j < nums[i].length; i++) {
        objects[i][j] = new Object(); // can contain any YOUR filling strategy
    }
}
Run Code Online (Sandbox Code Playgroud)


Muh*_*man 9

如果你想使用反射创建数组,那么你可以这样做:

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 
Run Code Online (Sandbox Code Playgroud)


Ole*_*hov 9

在Java 9中

使用不同IntStream.iterateIntStream.takeWhile方法:

int[] a = IntStream.iterate(10, x -> x <= 100, x -> x + 10).toArray();

Out: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]


int[] b = IntStream.iterate(0, x -> x + 1).takeWhile(x -> x < 10).toArray();

Out: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

在Java 10中

使用局部变量类型推断:

var letters = new String[]{"A", "B", "C"};
Run Code Online (Sandbox Code Playgroud)


278*_*184 8

声明一组对象引用:

class Animal {}

class Horse extends Animal {
    public static void main(String[] args) {

        /*
         * Array of Animal can hold Animal and Horse (all subtypes of Animal allowed)
         */
        Animal[] a1 = new Animal[10];
        a1[0] = new Animal();
        a1[1] = new Horse();

        /*
         * Array of Animal can hold Animal and Horse and all subtype of Horse
         */
        Animal[] a2 = new Horse[10];
        a2[0] = new Animal();
        a2[1] = new Horse();

        /*
         * Array of Horse can hold only Horse and its subtype (if any) and not
           allowed supertype of Horse nor other subtype of Animal.
         */
        Horse[] h1 = new Horse[10];
        h1[0] = new Animal(); // Not allowed
        h1[1] = new Horse();

        /*
         * This can not be declared.
         */
        Horse[] h2 = new Animal[10]; // Not allowed
    }
}
Run Code Online (Sandbox Code Playgroud)


Kha*_*d.K 7

数组是项目的顺序列表

int item = value;

int [] one_dimensional_array = { value, value, value, .., value };

int [][] two_dimensional_array =
{
  { value, value, value, .. value },
  { value, value, value, .. value },
    ..     ..     ..        ..
  { value, value, value, .. value }
};
Run Code Online (Sandbox Code Playgroud)

如果它是一个对象,那么它是相同的概念

Object item = new Object();

Object [] one_dimensional_array = { new Object(), new Object(), .. new Object() };

Object [][] two_dimensional_array =
{
  { new Object(), new Object(), .. new Object() },
  { new Object(), new Object(), .. new Object() },
    ..            ..               ..
  { new Object(), new Object(), .. new Object() }
};
Run Code Online (Sandbox Code Playgroud)

在对象的情况下,您需要将其分配null给初始化它们new Type(..),类String和类Integer是特殊情况,将按如下方式处理

String [] a = { "hello", "world" };
// is equivalent to
String [] a = { new String({'h','e','l','l','o'}), new String({'w','o','r','l','d'}) };

Integer [] b = { 1234, 5678 };
// is equivalent to
Integer [] b = { new Integer(1234), new Integer(5678) };
Run Code Online (Sandbox Code Playgroud)

通常,您可以创建M维度的数组

int [][]..[] array =
//  ^ M times [] brackets

    {{..{
//  ^ M times { bracket

//            this is array[0][0]..[0]
//                         ^ M times [0]

    }}..}
//  ^ M times } bracket
;
Run Code Online (Sandbox Code Playgroud)

值得注意的M是,就空间而言,创建维数阵列是昂贵的.因为当你在所有维度上创建一个M维数组时N,数组的总大小大于N^M,因为每个数组都有一个引用,并且在M维度上有一个(M-1)维引用数组.总大小如下

Space = N^M + N^(M-1) + N^(M-2) + .. + N^0
//      ^                              ^ array reference
//      ^ actual data
Run Code Online (Sandbox Code Playgroud)


Cha*_*nil 7

在Java 8中,您可以像这样使用.

String[] strs = IntStream.range(0, 15)  // 15 is the size
    .mapToObj(i -> Integer.toString(i))
    .toArray(String[]::new);
Run Code Online (Sandbox Code Playgroud)


Sam*_*ort 6

要创建类对象的数组,您可以使用java.util.ArrayList.定义一个数组:

public ArrayList<ClassName> arrayName;
arrayName = new ArrayList<ClassName>();
Run Code Online (Sandbox Code Playgroud)

为数组指定值:

arrayName.add(new ClassName(class parameters go here);
Run Code Online (Sandbox Code Playgroud)

从数组中读取:

ClassName variableName = arrayName.get(index);
Run Code Online (Sandbox Code Playgroud)

注意:

variableName是对数组的引用,意味着操作variableName将被操纵arrayName

for循环:

//repeats for every value in the array
for (ClassName variableName : arrayName){
}
//Note that using this for loop prevents you from editing arrayName
Run Code Online (Sandbox Code Playgroud)

for循环允许你编辑arrayName(传统的循环):

for (int i = 0; i < arrayName.size(); i++){
    //manipulate array here
}
Run Code Online (Sandbox Code Playgroud)


Kir*_*aev 5

为Java 8及更高版本声明和初始化。创建一个简单的整数数组:

int [] a1 = IntStream.range(1, 20).toArray();
System.out.println(Arrays.toString(a1));
// Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
Run Code Online (Sandbox Code Playgroud)

为[-50,50]之间的整数和双精度[0,1E17]创建一个随机数组:

int [] a2 = new Random().ints(15, -50, 50).toArray();
double [] a3 = new Random().doubles(5, 0, 1e17).toArray();
Run Code Online (Sandbox Code Playgroud)

2的幂次幂:

double [] a4 = LongStream.range(0, 7).mapToDouble(i -> Math.pow(2, i)).toArray();
System.out.println(Arrays.toString(a4));
// Output: [1.0, 2.0, 4.0, 8.0, 16.0, 32.0, 64.0]
Run Code Online (Sandbox Code Playgroud)

对于String [],您必须指定一个构造函数:

String [] a5 = Stream.generate(()->"I will not squeak chalk").limit(5).toArray(String[]::new);
System.out.println(Arrays.toString(a5));
Run Code Online (Sandbox Code Playgroud)

多维数组:

String [][] a6 = List.of(new String[]{"a", "b", "c"} , new String[]{"d", "e", "f", "g"})
    .toArray(new String[0][]);
System.out.println(Arrays.deepToString(a6));
// Output: [[a, b, c], [d, e, f, g]]
Run Code Online (Sandbox Code Playgroud)

  • 包括 -50,不包括 +50。此信息来自 [java api](https://docs.oracle.com/javase/8/docs/api/java/util/Random.html#ints-long-int-int-)“给定来源(包括)和绑定(独家)”。我使用 [wiki](https://en.wikipedia.org/wiki/Interval_(mathematics)#Classification_of_intervals) 的间隔声明。所以我认为它会更正确 [-50, 50) (2认同)

Syl*_*are 5

如果您所说的“数组”是指使用java.util.Arrays,则可以这样做:

List<String> number = Arrays.asList("1", "2", "3");

Out: ["1", "2", "3"]
Run Code Online (Sandbox Code Playgroud)

这个非常简单明了。

  • 列表不是数组 (3认同)

Aru*_*dev 5

这里有很多答案。我添加了一些棘手的方法来创建数组(从考试的角度来看,了解这一点是件好事)

  1. 声明并定义一个数组

    int intArray[] = new int[3];
    
    Run Code Online (Sandbox Code Playgroud)

    这将创建一个长度为 3 的数组。由于它包含基本类型 int,因此默认情况下所有值都设置为 0。例如,

    intArray[2]; // Will return 0
    
    Run Code Online (Sandbox Code Playgroud)
  2. 在变量名前使用方括号 []

    int[] intArray = new int[3];
    intArray[0] = 1;  // Array content is now {1, 0, 0}
    
    Run Code Online (Sandbox Code Playgroud)
  3. 初始化并向数组提供数据

    int[] intArray = new int[]{1, 2, 3};
    
    Run Code Online (Sandbox Code Playgroud)

    这次就不需要再提及盒子支架中的尺寸了。即使是一个简单的变体也是:

    int[] intArray = {1, 2, 3, 4};
    
    Run Code Online (Sandbox Code Playgroud)
  4. 长度为0的数组

    int[] intArray = new int[0];
    int length = intArray.length; // Will return length 0
    
    Run Code Online (Sandbox Code Playgroud)

    多维数组类似

    int intArray[][] = new int[2][3];
    // This will create an array of length 2 and
    //each element contains another array of length 3.
    // { {0,0,0},{0,0,0} }
    int lenght1 = intArray.length; // Will return 2
    int length2 = intArray[0].length; // Will return 3
    
    Run Code Online (Sandbox Code Playgroud)

在变量前使用方括号:

    int[][] intArray = new int[2][3];
Run Code Online (Sandbox Code Playgroud)

如果你在最后放一个方括号就绝对没问题了:

    int[] intArray [] = new int[2][4];
    int[] intArray[][] = new int[2][3][4]
Run Code Online (Sandbox Code Playgroud)

一些例子

    int [] intArray [] = new int[][] {{1,2,3},{4,5,6}};
    int [] intArray1 [] = new int[][] {new int[] {1,2,3}, new int [] {4,5,6}};
    int [] intArray2 [] = new int[][] {new int[] {1,2,3},{4,5,6}}
    // All the 3 arrays assignments are valid
    // Array looks like {{1,2,3},{4,5,6}}
Run Code Online (Sandbox Code Playgroud)

每个内部元素都具有相同的大小并不是强制性的。

    int [][] intArray = new int[2][];
    intArray[0] = {1,2,3};
    intArray[1] = {4,5};
    //array looks like {{1,2,3},{4,5}}

    int[][] intArray = new int[][2] ; // This won't compile. Keep this in mind.
Run Code Online (Sandbox Code Playgroud)

您必须确保如果您使用上述语法,则必须在方括号中指定前进方向的值。否则无法编译。一些例子:

    int [][][] intArray = new int[1][][];
    int [][][] intArray = new int[1][2][];
    int [][][] intArray = new int[1][2][3];
Run Code Online (Sandbox Code Playgroud)

另一个重要特征是协变

    Number[] numArray = {1,2,3,4};   // java.lang.Number
    numArray[0] = new Float(1.5f);   // java.lang.Float
    numArray[1] = new Integer(1);    // java.lang.Integer
   // You can store a subclass object in an array that is declared
   // to be of the type of its superclass.
   // Here 'Number' is the superclass for both Float and Integer.

   Number num[] = new Float[5]; // This is also valid
Run Code Online (Sandbox Code Playgroud)

重要提示:对于引用类型,存储在数组中的默认值为 null。


Zia*_*Zia 5

数组有两种基本类型。

静态数组:固定大小的数组(其大小应在开始时声明,以后不能更改)

动态数组:对此不考虑大小限制。(Java 中不存在纯动态数组。相反,最鼓励使用 List。)

要声明 Integer、string、float 等的静态数组,请使用以下声明和初始化语句。

int[] intArray = new int[10];
String[] intArray = new int[10];
float[] intArray = new int[10];

// Here you have 10 index starting from 0 to 9
Run Code Online (Sandbox Code Playgroud)

要使用动态特性,就必须使用List...List是纯动态Array,不需要在开头声明大小。下面是在 Java 中声明列表的正确方法 -

ArrayList<String> myArray = new ArrayList<String>();
myArray.add("Value 1: something");
myArray.add("Value 2: something more");
Run Code Online (Sandbox Code Playgroud)

  • 感谢@Matheus 改进我的答案。我请求您对此进行投票,以便它可以覆盖更多用户。 (2认同)