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 want to return two objects you usually want to return a single object that encapsulates the two objects instead.
You could return a List of NamedObject
objects like this:
public class NamedObject {
public final String name;
public final T object;
public NamedObject(String name, T object) {
this.name = name;
this.object = object;
}
}
Then you can easily return a List
.
Also: Why would you want to return a comma-separated list of names instead of a List
? Or better yet, return a Map
with the keys being the names and the values the objects (unless your objects have specified order, in which case a NavigableMap
might be what you want.