Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Declaring Arrays

Tags:

java

arrays

When I create a new array, I do something like this.

int[] anArray = {1, 2, 3};

But I've seen some people do something like.

int[] anArray = new int[] {1, 2, 3};

I understand what it does, but I don't understand the purpose of it. Is there a benefit of doing it one way over another?

Thanks

like image 975
Stripies Avatar asked Dec 26 '11 10:12

Stripies


3 Answers

There's no difference in behaviour where both are valid. They are covered in section 10.6 and 15.10 of the Java language specification.

However the first syntax is only valid when declaring a variable. So for example:

 public void foo(String[] args) {}

 ...

 // Valid
 foo(new String[] { "a", "b", "c" };

 // Invalid
 foo({"a", "b", "c"});

As for the purpose - the purpose of the first syntax is to allow variable declarations to be more concise... and the purpose of the second syntax is for general-purpose use as an expression. It would be odd to disallow the second syntax for variable declarations, just because the more concise syntax is available.

like image 196
Jon Skeet Avatar answered Sep 23 '22 03:09

Jon Skeet


One would use the second way, if the declaration should be done before the initialization.

int[] arr;
arr = { 2, 5, 6, 12, 13 };

Would not work, so you use:

int[] arr;
arr = new int[]{ 2, 5, 6, 12, 13 };

instead. Another way is to declare another variable:

int[] arr;
int[] tmparr = { 2, 5, 6, 12, 13 };
arr = tmparr;

So if you don't need to seperate the declaration from the initialization, it's only a matter of clean code (use either one consistently).

like image 32
markusschmitz Avatar answered Sep 23 '22 03:09

markusschmitz


They are almost the same thing, but the first is applicable for object assignment like:

int[] anArray = {1, 2, 3};

The other one is more globaly like

callingMyMethod(new Object[]{object1,object2});

The wrong syntax would be

callingMyMethod({object1,object2});

Let's take it further

These initialization are right:

Object[] objeto={new Object(), new Object()};
Object[] objeto=new Object[]{new Object(), new Object()};

Also right:

Object[] objeto;
objeto=new Object[]{new Object(), new Object()}

But as Jon suggested this is wrong:

Object[] objeto;
objeto={new Object(), new Object()};

Why? Array Initializer And Array Creation Expression

Anyway both of your syntax are correct. There is no benefit on one against the other.

Interesting reading on this subject:

Arrays on Oracle Official documentation

This have also been covered on this thread

like image 40
Necronet Avatar answered Sep 20 '22 03:09

Necronet