以下两个声明有什么区别吗?
int arr[] = new int [5];
和
int arr1[] = {1,2,3,4,5};
数组 arr1
是在栈上还是堆上声明的?
以下两个声明有什么区别吗?
int arr[] = new int [5];
和
int arr1[] = {1,2,3,4,5};
数组 arr1
是在栈上还是堆上声明的?
显而易见的区别是一个数组全是零,另一个包含[1..5]。
但这是唯一的区别。两者都是有5个元素的int数组,都是以相同的方式分配的。使用括号而不需要new
只是语法上的方便。
请注意,只有在声明数组时才能使用这种形式:
int[] blah = {}
但不是
int[] blah;
blah = {};
或者return {};
对象(包括数组)是在堆上分配的。
int i = 10;
是一个局部变量声明,那么10就在栈上;如果它是一个成员变量声明,那么它就在堆上。Integer i = 10;
等同于 Integer.valueOf(10)
,所以 i
引用的是堆中的值。 - Andy TurnerInteger i = 10
或int[] arr = {}
,则_引用_分配在栈上,但它们所指向的_对象_分配在堆上。这些引用只是可以被分配到另一个对象的指针。 - Klitos KyriacouMyObject[] myArray = new MyObject[3];
然后,您在堆上拥有一个数组对象,其中包含三个类型为MyObject的null引用,但您没有任何MyObject对象。下一步是创建一些MyObject对象并将它们分配给由myArray引用的数组中的索引位置。
myArray[0]=new MyObject();
myArray[1]=new MyObject();
myArray[2]=new MyObject();
总结:数组必须在构造时指定大小。JVM需要这个大小来为新的数组对象在堆上分配适当的空间。
我同意其他答案,无论您使用哪种声明方式,大多数情况下都会在堆上分配数组。不过,根据Can Java allocate a list on stack?中的顶级答案,“在特殊情况下,Java虚拟机可能会执行逃逸分析并决定将对象分配到堆栈上”。我相信这是真的。因此,对于您的问题的答案是:取决于情况。通常是在堆上分配。
new int [5]
can be used for both assignment and initialization, but {1, 2}
only can be used as declaration with initialization. (Note that new int[] {1, 2}
also can be used as both assignment and initialization)
new int [5]
sets all entries to zero, but {1, 2}
and new int[] {1, 2}
sets 1
and 2
in respective entries.
Both are on heap, you can save their object reference.
int arr[] = new int [5];
// arr: object reference to the array
or
int arr[] = {1, 2, 3, 4, 5};
// arr: object reference to the array
有用的资料:
int
字段的值存储在堆上的方式相同。 - Andy Turnernew int[]{1,2,3,4,5}
。 - Boris the Spider