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<
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:
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.cast
method is ok, but doesn't seem quite right.isInstance
are necessary.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.
PASS A HASH INTO THE METHOD AND POPULATE IT......
public void buildResponse(String data, Map response);
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
}
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);
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.