如何在Java中返回临时int数组 [英] How to return a temporary int array in Java

查看:268
本文介绍了如何在Java中返回临时int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

推荐答案


我有了使用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

When you write int[] ret = {0,1};, it is essentially a shortcut of writing int[] ret = new int[]{0,1};. From the 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
};


现在当你返回时你必须明确地写返回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数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆