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.ie
Arrays.toString(new int[]{1,2,3})
But Why can't thenum2
approach
if I call someFunction({1,2,3,4,4})
it throws an Error as
illegal start of an expression.
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 ?
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
I do not get what is a purpose, but consider this code to pass any int array to some fucntion:
somefucntion(Stream.iterate(1, i -> i + 1).limit(5).mapToInt(Integer::intValue).toArray());
void somefucntion(int[] ints) {
System.out.println(Arrays.toString(ints));
}
Number[] longs1 = new Long[] { 1L, 2L, 3L };
Number[] longs2 = new Long[] { 4L, 5L, 6L };
Number[] concatted = arrayConcat(longs1, longs2);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.