开发者

Array initialization differences java

开发者 https://www.devze.com 2023-02-04 19:48 出处:网络
What is the difference between the 开发者_开发知识库two following methods of array initialization:

What is the difference between the 开发者_开发知识库two following methods of array initialization:

  1. Object[] oArr = new Object[] {new Object(), new Object()};
  2. Object[] oArr = {new Object(), new Object()};

Is it related to heap/stack allocation?

Thanks!


None at all - they're just different ways of expressing the same thing.

The second form is only available in a variable declaration, however. For example, you cannot write:

foo.someMethod({x, y});

but you can write:

foo.someMethod(new SomeType[] { x, y });

The relevant bit of the Java language specification is section 10.6 - Array Initializers:

An array initializer may be specified in a declaration, or as part of an array creation expression (§15.10), creating an array and providing some initial values:


Absolutely identical. The second is allowed shorthand for the first (only when, as here, it is done as part of a variable declaration.


In Java all objects live in the heap, as arrays are objects in Java they lives in the stack.

for these two there is no difference in result, you 'll got two array objects with the same elements.

However sometimes you will encounter some situations where you can't use them, for example you don't know the elements of the array. then you get stuck with this form:

Object [] array=new Object[size];


There is a small and catchy difference still!

You can do

int[] arr;
arr= {1,2,3}; // Illegal

But you can very well do

int[] arr;
arr = new [] {1,2,3} //Legal

Also if you are to initialize later then you cannot do

int arr;
arr = new [] {1,2,3} //Illegal
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号