当我们创建一个类类型的对象时,new 运算符会在运行时分配内存。
说
myclass obj1 = new myclass();
这里 myclass()
定义了 myclass
的构造函数
但是
int arr1[4] = new int[];
new 分配内存但是,int[]
在这里做什么?
最佳答案
New allocates the memory but, what the int[] does here?
int[]
部分简单地指定了新分配的内存应该是什么类型。
但是,由于数组不能动态增长,因此编写 new int[]
没有意义(即使您指定了 int[4]
在声明中),你必须这样写
int arr1[] = new int[4];
或者像这样
int arr1[] = {1, 2, 3, 4};
JLS 中的相关部分:
关于java - java中创建数组时new操作符是干什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3952370/