java - 如何在 Java 中返回一个临时的 int 数组

标签 java arrays return

<分区>

我如何设法在 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/

相关文章:

java - Maven 在 CI 服务器上并发构建

java - 在 Java 中创建一个单义 id

javascript - typescript - 无法访问 Array.some 中的 "this"

macos - 为什么我的 x86 链表函数会抛出段错误?

java - 使用ant和自定义build.xml进行编译时出错,但在netbeans中工作

java - 在独立 Tomcat 服务器上,可以设置多少更高的值 - maxThreads 和 maxConnections?

c++ - 二维数组,一个已知,另一个未知

javascript - Jquery:代码未在 Rails 中的页面加载时执行

rust - 有没有办法做unwrap_or_return一个错误(任何错误)

c# - 返回已处理记录数的 SQL Server 存储过程