Return multiple values ​​in Java

Preamble: I know to use a list or other collections to return the result, but then I need to go through the list that displays the results: see the second example

Preamble 2: I am looking for an answer outside of "this is not supported in Java ..."


I am looking for a convenient way to return multiple objects from a Java method call.

Like in PHP:

list ($obj1, $obj2, ...) foobar();

I am really tired of passing holders in arguments, for example:

class Holder {
   int value;
}

Holder h1=new Holder();
Holder h2=new Holder();

and then:

o.foobar(h1,h2);

... it would be very interesting if someone came up with an elegant way to get around this.


List use

List<String> = foobar();

There are two drawbacks:

I must first pack the List on the side of the called house:

// this is on the callee side of the house
ArrayList<String> result = new ArrayList<String>
result.add("foo");
result.add("bar");

Then on the caller side I have to snatch the results:

// This is on the caller side
List<String> result = foobar();
String result1 = result.get(0);
String result2 = result.get(1); // this is not as elegant as the PHP equivalent

, , , , String, Integer, , ...

.

+5
6

- , . , :

public class T3<A, B, C> {
    A _1;
    B _2;
    C _3;
    T3(A _1, B _2, C _3) {
        this._1 = _1;
        this._2 = _2;
        this._3 = _3;
    }
}

- , :

public T3<String, Integer, Character> getValues() {
    return new T3<String, Integer, Character>("string", 0, 'c');
}

.

. , - Java. , N-Tuple.

java.util.AbstractMap.SimpleEntry :

return new SimpleEntry<String, Integer>("string", 0);

, :

, . , .

+8

, :

List<Holder> foobar();
+5
+4

, :

class Holder {
    int value1;
    String value2;
    Holder(int value1, String value2) {}
}

Holder foobar() {
    return new Holder(1, "bar");
}
+2

, . , , . , , . , , - , :

public int[] getUserId(){
    int[] returnArray = new int[3];
    returnArray[0] = getFirstPart();
    returnArray[1] = getSecondPart();
    returnArray[2] = getThirdPart();

    return returnArray;
}

, array[0], array[1] array[2]. , , , .

, - , . Java. . , , , , . (, ) . , , . - , , , .

+2
source

You can use any of the Collection class for this purpose. This Lesson will help you decide what is best for you.

+1
source

All Articles