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<
Before Java 5, I would kind of agree that the Map solution isn't ideal. It wouldn't give you compile time type checking so can cause issues at runtime. However, with Java 5, we have Generic Types.
So your method could look like this:
public Map<String, MyType> doStuff();
MyType of course being the type of object you are returning.
Basically I think that returning a Map is the right solution in this case because that's exactly what you want to return - a mapping of a string to an object.
Keep it simple and create a class for multiple result situation. This example accepts an ArrayList and a message text from a databasehelper getInfo.
Where you call the routine that returns multiple values you code:
multResult res = mydb.getInfo();
In the routine getInfo you code:
ArrayList<String> list= new ArrayList<String>();
add values to the list...
return new multResult("the message", list);
and define a class multResult with:
public class multResult {
public String message; // or create a getter if you don't like public
public ArrayList<String> list;
multResult(String m, ArrayList<String> l){
message = m;
list= l;
}
}
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<L, R> {
final L left;
final R right;
public Pair(L left, R right) {
this.left = left;
this.right = right;
}
public <T> T get(Class<T> param) {
return (T) (param == this.left.getClass() ? this.left : this.right);
}
public static <L, R> Pair<L, R> of(L left, R right) {
return new Pair<L, R>(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<ResultMessage, List<Customer>> getCustomers() {
List<Customer> list = new ArrayList<Customer>();
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<ResultMessage, List<Customer>> customerResult = _repository.getCustomers();
if (customerResult.get(ResultMessage.class).getCode() == 0) {
List<Customer> listOfCustomers = customerResult.get(List.class);
System.out.println("do SOMETHING with the list ;) ");
}else {
System.out.println("Raised Error... do nothing!");
}
}
Pass a list to your method and populate it, then return the String with the names, like this:
public String buildList(List<?> list) {
list.add(1);
list.add(2);
list.add(3);
return "something,something,something,dark side";
}
Then call it like this:
List<?> values = new ArrayList<?>();
String names = buildList(values);
Use of following Entry object Example :
public Entry<A,B> methodname(arg)
{
.......
return new AbstractMap.simpleEntry<A,B>(instanceOfA,instanceOfB);
}
Alternatively, in situations where I want to return a number of things from a method I will sometimes use a callback mechanism instead of a container. This works very well in situations where I cannot specify ahead of time just how many objects will be generated.
With your particular problem, it would look something like this:
public class ResultsConsumer implements ResultsGenerator.ResultsCallback
{
public void handleResult( String name, Object value )
{
...
}
}
public class ResultsGenerator
{
public interface ResultsCallback
{
void handleResult( String aName, Object aValue );
}
public void generateResults( ResultsGenerator.ResultsCallback aCallback )
{
Object value = null;
String name = null;
...
aCallback.handleResult( name, value );
}
}