问题描述
如何设法在Java中返回临时数组(为了保存代码行而不创建变量)。
How can I manage to return a temporary array in Java (in order to save code line, without creating a variable).
启动时,我可以使用
int[] ret = {0,1};
在退货时,我不能使用
return {0,1};
我是否错过了某些内容或是否有强制类型代码来执行此操作?
Do I miss something or is there a force typ-cast to do this?
我有想法使用 new int []
作为下面的答案。那么,在启动时我们不需要 new int []
的原因是什么?
I got the idea to use new int[]
as the answers below. While, what's the reason the we don't need new int[]
when doing initiation?
推荐答案
当你写 int [] ret = {0,1}; ,它本质上是写 int [] ret = new int [] {0,1}; 的快捷方式code>。来自:
When you write int[] ret = {0,1};
, it is essentially a shortcut of writing int[] ret = new int[]{0,1};
. From the doc:
int[] anArray = {
100, 200, 300,
400, 500, 600,
700, 800, 900, 1000
};
现在当你返回时你必须明确地写返回new int [] {0,1};
因为您没有对数组执行赋值操作(根据文档创建和初始化),因此您无法使用快捷方式。您必须使用 new
创建一个对象。
Now when you return you have to explicitly write return new int[]{0,1};
because you are not doing an assignment operation(create and initialize as per the doc) to the array and hence you cannot use the shortcut. You will have to create an object using new
.
这篇关于如何在Java中返回临时int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!