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<
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
}