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<
I followed a similar approach than the described in the other answers with a few tweaks based on the requirement I had, basically I created the following classes(Just in case, everything is Java):
public class Pair {
final L left;
final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public T get(Class param) {
return (T) (param == this.left.getClass() ? this.left : this.right);
}
public static Pair of(L left, R right) {
return new Pair(left, right);
}
}
Then, my requirement was simple, in the repository Class that reaches the DB, for the Get Methods than retrieve data from the DB, I need to check if it failed or succeed, then, if succeed, I needed to play with the returning list, if failed, stop the execution and notify the error.
So, for example, my methods are like this:
public Pair> getCustomers() {
List list = new ArrayList();
try {
/*
* Do some work to get the list of Customers from the DB
* */
} catch (SQLException e) {
return Pair.of(
new ResultMessage(e.getErrorCode(), e.getMessage()), // Left
null); // Right
}
return Pair.of(
new ResultMessage(0, "SUCCESS"), // Left
list); // Right
}
Where ResultMessage is just a class with two fields (code/message) and Customer is any class with a bunch of fields that comes from the DB.
Then, to check the result I just do this:
void doSomething(){
Pair> customerResult = _repository.getCustomers();
if (customerResult.get(ResultMessage.class).getCode() == 0) {
List listOfCustomers = customerResult.get(List.class);
System.out.println("do SOMETHING with the list ;) ");
}else {
System.out.println("Raised Error... do nothing!");
}
}