<分区>
我如何设法在 Java 中返回一个临时数组(为了节省代码行,而不创建变量)。
做印心的时候,我可以用
int[] ret = {0,1};
返回时无法使用
return {0,1};
我是否遗漏了什么或者是否有强制打字来做到这一点?
我想到了使用 new int[]
作为下面的答案。然而,我们在启动时不需要 new int[]
的原因是什么?
<分区>
我如何设法在 Java 中返回一个临时数组(为了节省代码行,而不创建变量)。
做印心的时候,我可以用
int[] ret = {0,1};
返回时无法使用
return {0,1};
我是否遗漏了什么或者是否有强制打字来做到这一点?
我想到了使用 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};的捷径
。来自doc :
Alternatively, you can use the shortcut syntax to create and initialize an array:
int[] anArray = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000 };
现在当你返回时,你必须显式地写 return new int[]{0,1};
因为你没有对数组进行赋值操作(根据文档创建和初始化)因此你不能使用快捷方式。您必须使用 new
创建一个对象。
关于java - 如何在 Java 中返回一个临时的 int 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35703237/