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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1200621/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 00:50:49  来源:igfitidea点击:

How do I declare and initialize an array in Java?

javaarrays

提问by bestattendance

How do I declare and initialize an array in Java?

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

采纳答案by glmxndr

You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array).

您可以使用数组声明或数组文字(但仅当您立即声明并影响变量时,数组文字不能用于重新分配数组)。

For primitive types:

对于原始类型:

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

// Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html

int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99
int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved.
int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort 

For classes, for example String, it's the same:

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

String[] myStringArray = new String[3];
String[] myStringArray = {"a", "b", "c"};
String[] myStringArray = new String[]{"a", "b", "c"};

The third way of initializing is useful when you declare the array first and then initialize it. The cast is necessary here.

第三种初始化方式在先声明数组然后初始化它时很有用。这里需要演员阵容。

String[] myStringArray;
myStringArray = new String[]{"a", "b", "c"};

回答by Thomas Owens

Alternatively,

或者,

// Either method works
String arrayName[] = new String[10];
String[] arrayName = new String[10];

That declares an array called arrayNameof size 10 (you have elements 0 through 9 to use).

这声明了一个arrayName大小为 10的数组(您可以使用元素 0 到 9)。

回答by Anirudh

There are various ways in which you can declare an array in Java:

在 Java 中有多种方法可以声明数组:

float floatArray[]; // Initialize later
int[] integerArray = new int[10];
String[] array = new String[] {"a", "b"};

You can find more information in the Sun tutorialsite and the JavaDoc.

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

回答by Nate

Type[] variableName = new Type[capacity];

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



Type variableName[] = new Type[capacity]; 

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

is also valid, but I prefer the brackets after the type, because it's easier to see that the variable's type is actually an array.

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

回答by Chet

I find it is helpful if you understand each part:

如果您了解每个部分,我发现它会有所帮助:

Type[] name = new Type[5];

Type[]is the typeof the variablecalled name ("name" is called the identifier). The literal "Type" is the base type, and the brackets mean this is the array type of that base. Array types are in turn types of their own, which allows you to make multidimensional arrays like Type[][](the array type of Type[]). The keyword newsays to allocate memory for the new array. The number between the bracket says how large the new array will be and how much memory to allocate. For instance, if Java knows that the base type Typetakes 32 bytes, and you want an array of size 5, it needs to internally allocate 32 * 5 = 160 bytes.

Type[]是名为 name的变量类型(“name”称为identifier)。文字“Type”是基类型,括号表示这是该基的数组类型。数组类型又是它们自己的类型,它允许您创建多维数组,例如(Type[] 的数组类型)。关键字表示为新数组分配内存。括号之间的数字表示新数组的大小以及要分配的内存量。例如,如果 Java 知道基本类型需要 32 个字节,而您想要一个大小为 5 的数组,则它需要在内部分配 32 * 5 = 160 个字节。Type[][]newType

You can also create arrays with the values already there, such as

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

int[] name = {1, 2, 3, 4, 5};

which not only creates the empty space but fills it with those values. Java can tell that the primitives are integers and that there are 5 of them, so the size of the array can be determined implicitly.

这不仅创建了空白空间,而且用这些值填充了它。Java 可以判断基元是整数,并且有 5 个整数,因此可以隐式确定数组的大小。

回答by Dave

Also, in case you want something more dynamic there is the List interface. This will not perform as well, but is more flexible:

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

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

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

String value = listOfString.get(0);
assertEquals( value, "foo" );

回答by Amit Bhandari

The following shows the declaration of an array, but the array is not initialized:

下面显示了一个数组的声明,但该数组没有被初始化:

 int[] myIntArray = new int[3];

The following shows the declaration as well as initialization of the array:

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

int[] myIntArray = {1,2,3};

Now, the following also shows the declaration as well as initialization of the array:

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

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

But this third one shows the property of anonymous array-object creation which is pointed by a reference variable "myIntArray", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created.

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

If we just write:

如果我们只写:

int[] myIntArray;

this is not declaration of array, but the following statement makes the above declaration complete:

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

myIntArray=new int[3];

回答by Isabella Engineer

There are two types of array.

有两种类型的数组。

One Dimensional Array

一维数组

Syntax for default values:

默认值的语法:

int[] num = new int[5];

Or (less preferred)

或(不太受欢迎)

int num[] = new int[5];

Syntax with values given (variable/field initialization):

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

int[] num = {1,2,3,4,5};

Or (less preferred)

或(不太受欢迎)

int num[] = {1, 2, 3, 4, 5};

Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all.

注意:为方便起见,最好使用 int[] num,因为它清楚地表明您在这里谈论的是数组。否则没有区别。一点也不。

Multidimensional array

多维数组

Declaration

宣言

int[][] num = new int[5][2];

Or

或者

int num[][] = new int[5][2];

Or

或者

int[] num[] = new int[5][2];

Initialization

初始化

 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;

Or

或者

 int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} };

Ragged Array (or Non-rectangular Array)

参差不齐的阵列(或非矩形阵列)

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

So here we are defining columns explicitly.
Another Way:

所以在这里我们明确定义列。
其它的办法:

int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} };

For Accessing:

访问:

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

Alternatively:

或者:

for (int[] a : num) {
  for (int i : a) {
    System.out.println(i);
  }
}

Ragged arrays are multidimensional arrays.
For explanation see multidimensional array detail at the official java tutorials

参差不齐的数组是多维数组。
有关解释,请参阅官方 Java 教程中的多维数组详细信息

回答by Muhammad Suleman

If you want to create arrays using reflections then you can do like this:

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

 int size = 3;
 int[] intArray = (int[]) Array.newInstance(int.class, size ); 

回答by HyperNeutrino

Take the primitive type intfor example. There are several ways to declare and intarray:

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

int[] i = new int[capacity];
int[] i = new int[] {value1, value2, value3, etc};
int[] i = {value1, value2, value3, etc};

where in all of these, you can use int i[]instead of int[] i.

在所有这些中,您可以使用int i[]代替int[] i.

With reflection, you can use (Type[]) Array.newInstance(Type.class, capacity);

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

Note that in method parameters, ...indicates variable arguments. Essentially, any number of parameters is fine. It's easier to explain with code:

请注意,在方法参数中,...表示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};

Inside the method, varargsis treated as a normal int[]. Type...can only be used in method parameters, so int... i = new int[] {}will not compile.

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

Note that when passing an int[]to a method (or any other Type[]), you cannot use the third way. In the statement int[] i = *{a, b, c, d, etc}*, the compiler assumes that the {...}means an int[]. But that is because you are declaring a variable. When passing an array to a method, the declaration must either be new Type[capacity]or new Type[] {...}.

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

Multidimensional Arrays

多维数组

Multidimensional arrays are much harder to deal with. Essentially, a 2D array is an array of arrays. int[][]means an array of int[]s. The key is that if an int[][]is declared as int[x][y], the maximum index is i[x-1][y-1]. Essentially, a rectangular int[3][5]is:

多维数组更难处理。本质上,二维数组是数组的数组。int[][]表示int[]s的数组。关键是如果 anint[][]声明为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]