不分配变量就返回数组 [英] Returning an array without assign to a variable
本文介绍了不分配变量就返回数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
java中是否有任何方法可以在不首先将其分配给变量的情况下返回新数组? 这是一个示例:
Is there any way in java to return a new array without assigning it first to a variable? Here is an example:
public class Data {
private int a;
private int b;
private int c;
private int d;
public int[] getData() {
int[] data = { a, b, c, d };
return data;
}
}
我想做这样的事情,但是不起作用:
I want to do something like this, but doesn't work:
public int[] getData() {
return {a, b, c, d};
}
推荐答案
即使您没有将数组分配给变量,您仍然需要创建该数组.试试这个:
You still need to create the array, even if you do not assign it to a variable. Try this:
public int[] getData() {
return new int[] {a,b,c,d};
}
您的代码示例不起作用,因为一方面,编译器仍然需要知道要通过静态初始化{}
创建的类型.
Your code sample did not work because the compiler, for one thing, still needs to know what type you are attempting to create via static initialization {}
.
这篇关于不分配变量就返回数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文