Question: How can I return more than one value from a method in Java?
Answer: Two easy ways exist to return multiple values from a function:
- Precondition:
Method 1 works only if the return values are all of the same type -- all values must be integers or booleans, and so on.
If your return values meet the precondition, simply return an array of values.
If your values are of different types, you could cast them all down to object and return them as an array of object. However, this proves dangerous work and requires your method's caller to possess too much knowledge of how the array is filled in.
- No precondition:
With method 2, simply create a high-level wrapper object. For example, if you would like to return an int, a float, and a
boolean, create the following wrapper:
public class SimpleWrapper
{
public SimpleWrapper(int I, float f, boolean b)
{
_anInt = I;
_aFloat = f;
_aBoolean = b;
}
public int getInt() { return _anInt; }
public float getFloat() { return _aFloat; }
public boolean getBoolean() { return _aBoolean; }
private int _anInt;
private float _aFloat;
private boolean _aBoolean;
}Of course, the class and method names should make more sense in your context.