public IntStr xyz() {
IntStr result = new IntStr();
result.i = 42;
result.s = "Hello Universe";
return result; }
Personally, I'd make IntStr have a suitable constructor so that the
above method body can be written in one line:
return new IntStr(42, "Hello Universe");
And I'd give it a better name.
When you want different kinds of things in an array, usually you are
either really looking to put a common supertype they're specialized
from in the array, or you're looking to have a fixed-size bunch of
different things used differently, which is better implemented as
instances of a class with a bunch of fields.
There are also other ways to return multiple things from a function.
In an either/or case you can (but it's evil) make all but one of them
a exception types, or objects wrapped in a exceptions, and throw them.
Sort them out in the caller with a try and bunch of catch clauses.
Since that's evil, you can also use a "union" as if from C, but it
will take the form of a Java class with a bunch of different fields, a
constructor for each field that sets it to a parameter and the others
to null, and methods to query the fields. The caller finds the non-
null to find out what type was in it.
Another possibility is mutating fields in an object, or the members of
a collection or array, passed as a parameter to the function. This can
lead to unclear code if it isn't carefully documented that the method
modifies the parameter, or if it's done cack-handedly enough. This is
useful if the function has a "return value" that is used immediately
when it returns (just return this) and also needs to communicate
something out-of-band (this uses the mutable collection or whatever).
The Builder pattern also passes as parameters objects that get
modified, sometimes, with methods that perform construction steps on a
data structure.
On the other hand, if a group of values is the logical return value of
the function, rather than a single value, then the function should
return a composite of some kind. An array, collection, or a custom
class with named fields for the components. It may be there's a design
problem whereby the method is trying to do multiple responsibilities
and should be divided and otherwise refactored, also; or it may be
that a logical extension of the way things are developing is for the
return type container object to become a "real" class with its own
behavior beyond querying the fields (or just making them public
final).
Use your design intuition to decide which approach to use in each
individual case where you find yourself wanting multiple returned
objects or composite returns.