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<
Regarding the issue about multiple return values in general I usually use a small helper class that wraps a single return value and is passed as parameter to the method:
public class ReturnParameter {
private T value;
public ReturnParameter() { this.value = null; }
public ReturnParameter(T initialValue) { this.value = initialValue; }
public void set(T value) { this.value = value; }
public T get() { return this.value; }
}
(for primitive datatypes I use minor variations to directly store the value)
A method that wants to return multiple values would then be declared as follows:
public void methodThatReturnsTwoValues(ReturnParameter nameForFirstValueToReturn, ReturnParameter nameForSecondValueToReturn) {
//...
nameForFirstValueToReturn.set("...");
nameForSecondValueToReturn.set("...");
//...
}
Maybe the major drawback is that the caller has to prepare the return objects in advance in case he wants to use them (and the method should check for null pointers)
ReturnParameter nameForFirstValue = new ReturnParameter();
ReturnParameter nameForSecondValue = new ReturnParameter();
methodThatReturnsTwoValues(nameForFirstValue, nameForSecondValue);
Advantages (in comparison to other solutions proposed):