[java] Return different type of data from a method in java?

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

This question is related to java return return-type

The answer is


The class you're looking for already exists. Map.Entry:

public static Entry<Integer,String> myMethod(){
    return new SimpleEntry<>(12, "value");
}

And later:

Entry<Integer,String> valueAndIndex = myMethod();
int index = valueAndIndex.getKey();
String value = valueAndIndex.getValue();

It's just a simple two-field data structure that stores a key and value. If you need to do any special processing, store more than two fields, or have any other fringe case, you should make your own class, but otherwise, Map.Entry is one of the more underutilized Java classes and is perfect for situations like these.


This can be one of the solution. But your present solution is good enough. You can also add new variables and still keep it clean, which cannot be done with present code.

private static final int INDEX_OF_STRING_PARAM = 0;
private static final int INDEX_OF_INT_PARAM = 1;

public static Object[] myMethod() {
    Object[] values = new Object[2];
    values[INDEX_OF_STRING_PARAM] = "value";
    values[INDEX_OF_INT_PARAM] = 12;
    return values;
}

you can have the return as an object. You create that object 'on fly' in your

function: if(int) 
 return new object(){
   int nr=..
}

same for string. But I am concerned that is an expensive solution...


@ruchira ur solution it self is best.But i think if it is only about integer and a string we can do it in much easy and simple way..

 class B {   
    public String myfun() {         
        int a=2;           //Integer .. you could use scanner or pass parameters ..i have simply assigned
        String b="hi";      //String
        return Integer.toString(a)+","+b; //returnig string and int with "," in middle          
    }       
}

class A {    
    public static void main(String args[]){

        B obj=new B();  // obj of class B with myfun() method  
        String returned[]=obj.myfun().split(",");
             //splitting integer and string values with "," and storing them in array   
        int b1=Integer.parseInt(returned[0]); //converting first value in array to integer.    
        System.out.println(returned[0]); //printing integer    
        System.out.println(returned[1]); //printing String
    }
}

i hope it was useful.. :)



public ArrayList divineCast(String object) {  
        try
        {
            Integer result = Integer.parseInt(object);
            ArrayList<Integer> generic = new   ArrayList<Integer>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Integer
        }
        try
        {
            Float result = Float.parseFloat(object);
            ArrayList<Float> generic = new   ArrayList<Float>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Float
        }
        try
        {
            Double result = Double.parseDouble(object);
            ArrayList<Double> generic = new   ArrayList<Double>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a double
        }
        try
        {
            Boolean result = Boolean.parseBoolean(object);
            ArrayList<Boolean> generic = new   ArrayList<Boolean>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a Boolean
        }
        try
        {
            String result = String.valueOf(object);
            ArrayList<String> generic = new   ArrayList<String>();
            generic.add(result);
            return generic;
        }
        catch(Exception e)
        {
            //not a String
        }
        return null;

    }

Then you can call then function as so

String test1 = "0.90854938";
String test2 = "true";
System.out.println(divineCast(test1).get(0));
System.out.println(divineCast(test1).get(0).getClass());
System.out.println(divineCast(test2).get(0));
System.out.println(divineCast(test2).get(0).getClass());

Java doesn't force you to declare the type of ArrayList you are returning in the function declaration, so you can return an ArrayList of any type.


I know this is late but I thought it'd be helpful to someone who'll come searching for an answer to this. You can use a Bundle to return multiple datatype values without creating another method. I tried it and worked perfectly.

In Your MainActivity where you call the method:

Bundle myBundle = method();
String myString = myBundle.getString("myS");
String myInt = myBundle.getInt("myI");

Method:

public Bundle method() {
    mBundle = new Bundle();
    String typicalString = "This is String";
    Int typicalInt = 1;
    mBundle.putString("myS", typicalString);
    mBundle.putInt("myI", typicalInt);
    return mBundle;
}

P.S: I'm not sure if it's OK to implement a Bundle like this, but for me, it worked out perfectly.


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.


Method overloading can come in handy here Like:

<code>
public class myClass 
{
    int add(int a, int b) 
    {
         return (a + b);
    }

    String add(String a, String b)
    {
         return (c + d);
    }

    public static void main(String args[]) 
    {
        myClass ob1 = new myClass);
        ob1.add(2, 3);
        //will return 5
        ob1.add("Hello, ", "World!");
        //will return Hello, World!
    }

}


I just want to put my view

So you need to create a generic Return type and implemented by different types of concret return types. The Service class can create different types of objects concrete class and return as a generic type.

public interface GenericReturnType{
    public static RETURN_TYPE enum{
        MACHINE, PERSON;    
    }
    public RETURN_TYPE getReturnType();
}

public class PersonReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return PERSON;
    }
    public String getAddress(){
        return something;
    }
}

public class MachineReturnType implements GenericReturnType{
    // CONSTRUCTORS //

    // GETTRE AND SETTER //

    public RETURN_TYPE getReturnType(){
        return MACHINE;
    }
    public String getManufatureName(){
        return something;
    }
}


public class TestService{
    public GenericReturnType getObject(// some input //){
        GenericReturnType obj ;
        if(// some code //){
            obj = new  PersonReturnType();
            // some code //
        }
        if(// some code //){
            obj = new  MachineReturnType();
            // some code //
        }
        return obj;
    }
}

public class TestDriver{
    TestService service = new TestService();
    GenericReturnType genObj = TestService.getObject(// some input //);
    if(genObj.getReturnType() == RETURN_TYPE.MACHINE){
        // SOME CODE // 
    }
    if(genObj.getReturnType() == RETURN_TYPE.PERSON){
        // SOME CODE // 
    }
}

Generally if you are not sure of what value you will end up returning, you should consider using return-type as super-class of all the return values. In this case, where you need to return String or int, consider returning Object class(which is the base class of all the classes defined in java).

But be careful to have instanceof checks where you are calling this method. Or else you may end up getting ClassCastException.

public static void main(String args[]) {
        Object obj = myMethod(); // i am calling static method from main() which return Object
    if(obj instanceof String){
    // Do something
    }else(obj instance of Integer) {
    //do something else
     }

the approach you took is good. Just Implementation may need to be better. For instance ReturningValues should be well defined and Its better if you can make ReturningValues as immutable.

// this approach is better
public static ReturningValues myMethod() {
    ReturningValues rv = new ReturningValues("value", 12);
    return rv;
}


public final class ReturningValues {
    private final String value;
    private final int index;


    public ReturningValues(String value, int index) {
      this.value = value;
      this.index = index;
     }

} 

Or if you have lots of key value pairs you can use HashMap then

public static Map<String,Object> myMethod() {
  Map<String,Object> map = new HashMap<String,Object>();
  map.put(VALUE, "value");
  map.put(INDEX, 12);
  return Collections.unmodifiableMap(map); // try to use this 
}

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

}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to return

Method Call Chaining; returning a pointer vs a reference? How does Python return multiple values from a function? Return multiple values from a function in swift Python Function to test ping Returning string from C function "Missing return statement" within if / for / while Difference between return 1, return 0, return -1 and exit? C# compiler error: "not all code paths return a value" How to return a struct from a function in C++? Print raw string from variable? (not getting the answers)

Examples related to return-type

How to specify multiple return types using type-hints Return from lambda forEach() in java Return different type of data from a method in java? Apply pandas function to column to create multiple new columns? C++: variable 'std::ifstream ifs' has initializer but incomplete type Returning anonymous type in C# How do I make the return type of a method generic? How to return result of a SELECT inside a function in PostgreSQL? Can two Java methods have same name with different return types? What should main() return in C and C++?