-4

In java i would like to create a method that can return multiple objects like a couple of int values, strings, float , double etc. what is the way to do this?

Panos Kalatzantonakis
  • 12,525
  • 8
  • 64
  • 85
user3740154
  • 89
  • 1
  • 2
  • 6

2 Answers2

0

You need to create a class that encapsulates all you desired return types.

Like the following:

public class MyReturnValues {
    private int integer1;
    private int integer2;
    private String myString;
    //etc

    public MyReturnValues() {
    }

    public MyReturnValues(int integer1, int integer2, String myString) {
        this.integer1 = integer1;
        this.integer2 = integer2;
        this.myString = myString;
    }

    public int getInteger1() {
        return integer1;
    }

    public void setInteger1(int integer1) {
        this.integer1 = integer1;
    }

    public int getInteger2() {
        return integer2;
    }

    public void setInteger2(int integer2) {
        this.integer2 = integer2;
    }

    public String getMyString() {
        return myString;
    }

    public void setMyString(String myString) {
        this.myString = myString;
    }
}

And then you set this as your return value for your method:

public MyReturnValues myMethod() {
//your code that creates the MyReturnValue using constructor or setter methods
}

To access the values, just call the get method on the class:

int integer1 = myMethod().getInteger1();
//etc
Gabriel Ruiu
  • 2,753
  • 2
  • 19
  • 23
0

Use array as return type

public int[] returnIntValues(){
    int[] arr = {1,2,3,4,5};
    return arr;
}
Jeeshu Mittal
  • 445
  • 3
  • 14