什么是在创建数组时使用”new”和不使用的区别?

huangapple go评论85阅读模式
英文:

What's difference between use new or not when i create an array?

问题

我知道有两种方法可以使用给定的初始值创建数组:

  1. int[] ary1 = new int[]{1,2,3,4};

  2. int[] ary1 = {1,2,3,4};

这两者之间究竟有什么区别呢?

英文:

I know there are two ways to create an array with given initial value

1.int[] ary1 = new int[]{1,2,3,4};

2.int[] ary1 = {1,2,3,4};

What exactly difference between those?

答案1

得分: 2

没有在您的示例中有任何区别。

但是,new type[] 提供了一个额外的功能 - 数组长度:

就像这样:

String[] names = new String[5];

这将创建一个新的 String 数组,具有容纳 5 个项的能力。如果其中一个项目没有被填充,它将返回 null

英文:

There is no difference in your example.

However, there is one extra feature that new type[] provides - array length:

Like so:

String[] names = new String[5];

Which makes a new String array with the capacity to hold 5 items. If one of the items is not populated, it will return null.

答案2

得分: 1

你的两个语句都会创建并初始化一个数组。然而,下面的示例展示了一个区别:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        print(new int[] { 1, 2, 3, 4 });
        // print({ 1, 2, 3, 4 }); // 无法编译通过
    }

    static void print(int[] arr) {
        System.out.println(Arrays.toString(arr));
    }
}
英文:

Both of your statements will create and initialize an array. However, the following example illustrates a difference:

import java.util.Arrays;

public class Main {
	public static void main(String[] args) {
		print(new int[] { 1, 2, 3, 4 });
		// print({ 1, 2, 3, 4 });// Won't be compiled
	}

	static void print(int[] arr) {
		System.out.println(Arrays.toString(arr));
	}
}

答案3

得分: 0

以下是翻译好的内容:

两者均等如下。

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

{}方法只能在数组声明时使用。因此,

int[] ary1;
ary1 = {1,2,3,4}; // 不允许。

也不是

for (int a : {1,2,3,4}) {
  // 做一些事情
}

而应该是

for (int a : new int[] {1,2,3,4}) {
  // 做一些事情
}
英文:

Both of the following are equivalent.

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

But the {} method can only be used when the array is declared. So

int[] ary1;
ary1 = {1,2,3,4}; // not permitted.

Nor is

for (int a : {1,2,3,4}) {
  // do something
}

It has to be

for (int a : new int[] {1,2,3,4}) {
  // do something
}


</details>



huangapple
  • 本文由 发表于 2020年9月23日 23:46:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/64031673.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定