Simplifying Array declaration in Java

Aashish Pawar :

Consider following array declarations,

int[] num2 = {1, 2, 3, 4, 5};
int[] num3 = new int[]{1, 2, 3, 4, 5};

System.out.println(Arrays.toString(num2));
System.out.println(Arrays.toString(num3));

So for the num3 if I passed directly the right hand side declaration to a functions its valid.

i.e. Arrays.toString(new int[]{1,2,3}) But Why can't the num2 approach

if I call someFunction({1,2,3,4,4}) it throws an Error as

illegal start of an expression.

If both declarations are valid then why can't I use it in arguments of method ?

I was trying to simply the approach , when passing some temporary array to a function such as

somefunction(new int[]{1,2,3,4})

Is it possible simplify this in java ? any java 8 tricks ?

YCF_L :

You have to create an instance to pass it to the method, for example :

someFunction(new int[]{});

It doesn't work in your case, because you passe only the type int[] and this is not correct.

Is it possible simplify this in java ? any java 8 tricks ?

I want to use it as somefunc({1,2,3,4})

Then you can use varargs, like so :

ReturnType someFunction(int... a){}

then you call this method like so:

someFunction(1, 2, 3, 4); // valid 
someFunction(new int[]{1, 2, 3, 4}); // valid
someFunction(num2); // valid

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=297382&siteId=1