例如,可以将字符数组初始化为:
char[] myArray = new char[3];
myArray = {'a', 'b', 'c'};
或者可以将字符数组初始化为:
char[] myArray = {'a','b', 'c'};
使用"new"方法有什么好处?
顺便说一下,在第一个示例中,为什么我也可以分配 { ... } 集而不将其传递给构造函数方法(在括号中)?
char[] myArray = new char[] {'a', 'b', 'c'};
最佳答案
{and}
是一种快捷语法,此处数组的长度由 { and }
之间提供的值的数量决定。
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/