How to return multiple objects from a Java method?

前端 未结 25 3093
眼角桃花
眼角桃花 2020-11-21 23:55

I want to return two objects from a Java method and was wondering what could be a good way of doing so?

The possible ways I can think of are: return a HashMap<

相关标签:
25条回答
  • 2020-11-22 00:23

    If you know you are going to return two objects, you can also use a generic pair:

    public class Pair<A,B> {
        public final A a;
        public final B b;
    
        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    };
    

    Edit A more fully formed implementation of the above:

    package util;
    
    public class Pair<A,B> {
    
        public static <P, Q> Pair<P, Q> makePair(P p, Q q) {
            return new Pair<P, Q>(p, q);
        }
    
        public final A a;
        public final B b;
    
        public Pair(A a, B b) {
            this.a = a;
            this.b = b;
        }
    
        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((a == null) ? 0 : a.hashCode());
            result = prime * result + ((b == null) ? 0 : b.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }
            if (obj == null) {
                return false;
            }
            if (getClass() != obj.getClass()) {
                return false;
            }
            @SuppressWarnings("rawtypes")
            Pair other = (Pair) obj;
            if (a == null) {
                if (other.a != null) {
                    return false;
                }
            } else if (!a.equals(other.a)) {
                return false;
            }
            if (b == null) {
                if (other.b != null) {
                    return false;
                }
            } else if (!b.equals(other.b)) {
                return false;
            }
            return true;
        }
    
        public boolean isInstance(Class<?> classA, Class<?> classB) {
            return classA.isInstance(a) && classB.isInstance(b);
        }
    
        @SuppressWarnings("unchecked")
        public static <P, Q> Pair<P, Q> cast(Pair<?, ?> pair, Class<P> pClass, Class<Q> qClass) {
    
            if (pair.isInstance(pClass, qClass)) {
                return (Pair<P, Q>) pair;
            }
    
            throw new ClassCastException();
    
        }
    
    }
    

    Notes, mainly around rustiness with Java & generics:

    • both a and b are immutable.
    • makePair static method helps you with boiler plate typing, which the diamond operator in Java 7 will make less annoying. There's some work to make this really nice re: generics, but it should be ok-ish now. (c.f. PECS)
    • hashcode and equals are generated by eclipse.
    • the compile time casting in the cast method is ok, but doesn't seem quite right.
    • I'm not sure if the wildcards in isInstance are necessary.
    • I've just written this in response to comments, for illustration purposes only.
    0 讨论(0)
  • 2020-11-22 00:23

    In C++ (STL) there is a pair class for bundling two objects. In Java Generics a pair class isn't available, although there is some demand for it. You could easily implement it yourself though.

    I agree however with some other answers that if you need to return two or more objects from a method, it would be better to encapsulate them in a class.

    0 讨论(0)
  • 2020-11-22 00:23

    PASS A HASH INTO THE METHOD AND POPULATE IT......

    public void buildResponse(String data, Map response);

    0 讨论(0)
  • 2020-11-22 00:26

    This is not exactly answering the question, but since every of the solution given here has some drawbacks, I suggest to try to refactor your code a little bit so you need to return only one value.

    Case one.

    You need something inside as well as outside of your method. Why not calculate it outside and pass it to the method?

    Instead of:

    [thingA, thingB] = createThings(...);  // just a conceptual syntax of method returning two values, not valid in Java
    

    Try:

    thingA = createThingA(...);
    thingB = createThingB(thingA, ...);
    

    This should cover most of your needs, since in most situations one value is created before the other and you can split creating them in two methods. The drawback is that method createThingsB has an extra parameter comparing to createThings, and possibly you are passing exactly the same list of parameters twice to different methods.


    Case two.

    Most obvious solution ever and a simplified version of case one. It's not always possible, but maybe both of the values can be created independently of each other?

    Instead of:

    [thingA, thingB] = createThings(...);  // see above
    

    Try:

    thingA = createThingA(...);
    thingB = createThingB(...);
    

    To make it more useful, these two methods can share some common logic:

    public ThingA createThingA(...) {
        doCommonThings(); // common logic
        // create thing A
    }
    public ThingB createThingB(...) {
        doCommonThings(); // common logic
        // create thing B
    }
    
    0 讨论(0)
  • 2020-11-22 00:27

    While in your case, the comment may be a good way to go, in Android, you can use Pair . Simply

    return new Pair<>(yourList, yourCommaSeparatedValues);
    
    0 讨论(0)
  • 2020-11-22 00:28

    All possible solutions will be a kludge (like container objects, your HashMap idea, “multiple return values” as realized via arrays). I recommend regenerating the comma-separated list from the returned List. The code will end up being a lot cleaner.

    0 讨论(0)
提交回复
热议问题