本文介绍了在 Java 中不使用“new"关键字声明数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下两个声明有什么区别吗?
Is there any difference between the following two declarations?
int arr[] = new int [5];
和
int arr1[] = {1,2,3,4,5};
arr1
是声明在栈上还是堆上?
Is arr1
declared on stack or on the heap?
推荐答案
有一个明显的区别,一个全零,另一个包含 [1..5].
There is the obvious difference that one has all zeros, and the other contains [1..5].
但这是唯一的区别.两者都是 5 个元素的 int 数组,它们的分配方式相同.用大括号声明只是语法上的方便,没有 new
.
But that's the only difference. Both are 5-element int arrays, both are allocated in the same way. It is mere syntactic convenience to declare with the braces and no new
.
注意这种形式只能在声明数组时使用:
Note that this form can only be used when the array is declared:
int[] blah = {}
但不是
int[] blah;
blah = {};
或
return {};
对象(数组就是对象)在堆上分配.
Objects (arrays are objects) are allocated on the heap.
这篇关于在 Java 中不使用“new"关键字声明数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!