简体   繁体   English

在同一行中从同一源初始化多个变量(JAVA)

[英]Initializing multiple variables from same source in one line (JAVA)

Given the method: 给定方法:

private Object[] method(){
    //run some codes
    return new Object[]{Obj1, Obj2};
}

Note that 2 different runs will give unique outputs therefore the following will be incorrect 请注意,两次不同的运行将给出唯一的输出,因此以下内容将不正确

Object obj1run1 = method()[0], obj2run1 = method()[1];
//Because the method will be run 2 times with 2 unique results;

I know i can solve my issues by doing: 我知道我可以通过以下方式解决问题:

Object hold[] = method();
obj1run1 = hold[0];
obj2run1 = hold[1];

But I am looking for a minimal and quick way of writing the code, like say: 但是我正在寻找一种最小和快速的方式来编写代码,例如:

(obj1run1, obj2run1) = method();
//saw this somewhere but doesnt work on Java

So my question (using the above example): How do i assign contents of an array into multiple variables in as little lines of codes as possible? 所以我的问题(使用上面的示例): 如何以尽可能少的代码行将数组的内容分配给多个变量?

 (obj1run1, obj2run1) = method(); 

This syntax, commonly referred as reading a tuple , is available in several other languages (Swift, latest C#, etc.) but not in Java . 这种语法通常称为“ 读取元组” ,它可用其他几种语言(Swift,最新的C#等)提供, 但Java不可用

Although your solution works fine, you may be better off creating a special class for returning your particular tuple. 尽管您的解决方案运行良好,但最好创建一个特殊的类来返回您的特定元组。 Since the two objects that you return are related in some way, at least by virtue of being returned from the same method, it may be a good idea to define a class for them: 由于您返回的两个对象至少在某种程度上是通过从同一方法返回而以某种方式关联的,因此最好为它们定义一个类:

class HoldingPair {
    private final Object first;
    private final Object second;
    public Object getFirst() { return first; }
    public Object getSecond() { return second; }
    public HoldingPair(Object a, Object b) {
        first = a;
        second = b;
    }
    ... // hashCode, equal, toString
}

Now your method could return a HoldingPair object, which you would be able to use directly, for example 现在您的方法可以返回一个HoldingPair对象,您可以直接使用它,例如

HoldingPair hold = method();
...
if (hold.getFirst() != null) {
    ...
}
if (hold.getSecond() != null) {
    ...
}

You can mix both of your solutions but you can't do multiple affectation like in python or scala. 您可以混合使用两种解决方案,但不能像python或scala那样进行多种操作。 Depending of the context, you can always find something pretty to do it. 根据上下文,您总是可以找到一些不错的方法。 The minimal way to do it is: 最小的方法是:

Object hold[] = method();
Object obj1run1 = hold[0], obj2run1 = hold[1];

But you can create your own Tuple if semantically, there is a strong link between those two Objects. 但是,如果在语义上,这两个对象之间存在牢固的联系,则可以创建自己的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM