简体   繁体   English

简化 Java 中的数组声明

[英]Simplifying Array declaration in Java

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.因此,对于num3如果我直接将右侧声明传递给一个有效的函数。

ie Arrays.toString(new int[]{1,2,3}) But Why can't the num2 approachArrays.toString(new int[]{1,2,3})但是为什么不能使用num2方法

if I call someFunction({1,2,3,4,4}) it throws an Error as如果我调用someFunction({1,2,3,4,4})它会抛出一个错误

illegal start of an expression.表达式的非法开始。

If both declarations are valid then why can't I use it in arguments of method ?如果两个声明都有效,那么为什么我不能在 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 ?是否可以在 java 中简化它? any java 8 tricks ?任何 Java 8 技巧?

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.它在您的情况下不起作用,因为您只传递类型int[]而这是不正确的。

Is it possible simplify this in java ?是否可以在 java 中简化它? any java 8 tricks ?任何 Java 8 技巧?

I want to use it as somefunc({1,2,3,4})我想用它作为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:我不明白什么是目的,但考虑这段代码将任何 int 数组传递给某些功能:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM