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?
Asked
Active
Viewed 96 times
-4
-
2Define a class and return an instance of it. – Oliver Charlesworth Jun 14 '14 at 10:33
-
Start learning about arrays and collections. – Robby Cornelissen Jun 14 '14 at 10:33
-
Is there some clear format(e.g int,int,string,double) ? – Scis Jun 14 '14 at 10:33
-
integers, floats and doubles aren't objects! – Tobias Jun 14 '14 at 10:33
2 Answers
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