java - 在 java 中,使用 "new"初始化数组有什么好处?

标签 java arrays constructor

例如,可以将字符数组初始化为:

char[] myArray = new char[3];
myArray = {'a', 'b', 'c'};

或者可以将字符数组初始化为:

char[] myArray = {'a','b', 'c'};

使用"new"方法有什么好处?

顺便说一下,在第一个示例中,为什么我也可以分配 { ... } 集而不将其传递给构造函数方法(在括号中)?

char[] myArray = new char[] {'a', 'b', 'c'};

最佳答案

{and} 是一种快捷语法,此处数组的长度由 { and } 之间提供的值的数量决定。

来自 Arrays Oracle docs

One way to create an array is with the new operator. The next statement in the ArrayDemo program allocates an array with enough memory for ten integer elements and assigns the array to the anArray variable.

// create an array of integers
anArray = new int[10];

Alternatively, you can use the shortcut syntax to create and initialize an array:

int[] anArray = { 
100, 200, 300,
400, 500, 600, 
700, 800, 900, 1000
};

关于java - 在 java 中,使用 "new"初始化数组有什么好处?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12363099/

相关文章:

php - SET a1 WHERE a AND b1 WHERE b AND c1 WHERE c, 等等

python - 从索引的列/行数组中填充出现的矩阵

JavaScript 构造函数参数类型

java - 向现有 mongo 数组添加新值

运行appium脚本时出现java.lang.ClassNotFoundException

java - 如何在 Java 中动态创建类型实例

dll - 首先调用 DllMain() 还是全局静态对象构造函数?

java - 如何根据 myobject 的属性对 ArrayList<myobject> 进行排序

c# - IEnumerable<T> ToArray 用法 - 它是副本还是指针?

c# - 对象不能从 DBNull 转换为构造函数中的其他类型