public static void main(String args[]) { myMethod(); // i am calling static method from main() }
.
public static ? myMethod(){ // ? = what should be the return type return value;// is String return index;// is int }
myMethod()
will return String and int value. So take these returning values from main()
i came up with following solution.
create a class call ReturningValues
public class ReturningValues { private String value; private int index; // getters and setters here }
and change myMethod()
as follows.
public static ReturningValues myMethod() { ReturningValues rv = new ReturningValues(); rv.setValue("value"); rv.setIndex(12); return rv; }
Now my question,is there any easier way to achieve this??
Java doesn't support multi-value returns but returning multiple values with different datatype in Java is possible via creating a class. In above case Test and encapsulating encapsulating all returned types into that class in above case a double and an integer value is to be returned.
The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean.
You can return only one value in Java. If needed you can return multiple values using array or an object.
I create various return types using enum. It doesn't defined automatically. That implementation look like factory pattern.
public enum SmartReturn { IntegerType, DoubleType; @SuppressWarnings("unchecked") public <T> T comeback(String value) { switch (this) { case IntegerType: return (T) Integer.valueOf(value); case DoubleType: return (T) Double.valueOf(value); default: return null; } } }
Unit Test:
public class MultipleReturnTypeTest { @Test public void returnIntegerOrString() { Assert.assertTrue(SmartReturn.IntegerType.comeback("1") instanceof Integer); Assert.assertTrue(SmartReturn.DoubleType.comeback("1") instanceof Double); } }
No. Java methods can only return one result (void
, a primitive, or an object), and creating a struct
-type class like this is exactly how you do it.
As a note, it is frequently possible to make classes like your ReturningValues
immutable like this:
public class ReturningValues { public final String value; public final int index; public ReturningValues(String value, int index) { this.value = value; this.index = index; } }
This has the advantage that a ReturningValues
can be passed around, such as between threads, with no concerns about accidentally getting things out of sync.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With