简体   繁体   中英

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 .

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 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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