0

Possible Duplicate:
How to return multiple objects from a Java method?

Is there any way to return multiple defferent objects from a Java method

for example i want return string ,int ,object ,.. etc

thanks

Community
  • 1
  • 1
AAlkhabbaz
  • 197
  • 1
  • 3
  • 13

3 Answers3

5

You can return a Map<Class, Object> containing the resulting objects' types mapped with their values.

public Map<Class, Object> doSomeStuff(){
  Map<Class, Object> map = HashMap<Class, Object>();
  map.put(String.getClass(), "This is an example");
  map.put(Object.getClass(), new Object());
  //...
  return map;
}

// You can then retrieve all results by
String stringVal = map.get(String.getClass());
Object objectVal = map.get(Object.getClass());
GETah
  • 20,922
  • 7
  • 61
  • 103
  • Which one of these solution is better? your's or this: http://stackoverflow.com/questions/457629/how-to-return-multiple-objects-from-a-java-method – Dr.jacky Jul 12 '14 at 12:58
  • They are the same. Notice the most voted answer on the one you linked to here states that using a map is better - that's what my answer here explains :) – GETah Jul 12 '14 at 13:58
2

Make a new class and return that class.

//Give this a more descriptive name reflecting what it REALLY is.
public static class ReturnData{
protected String foo
protected int bar

public ReturnData(String foo, int Bar) {
  ...
}
String getFoo() {
  ...
}
int getBar() {
  ...
}

Then in your method instantiate the object with what you want to return

MyMethod(...){
   ...
   ...
   return new ReturnData(foo, bar);
}

Viola! You returned both foo and bar at same time.

Desmond Zhou
  • 1,369
  • 1
  • 11
  • 18
1

Not explicitly. You can make your own class that contains eveything, and return that, or you can return some form of Object array (Object[]) or list (like an ArrayList) that contains everything, but that is not recommended.

EDIT: Also you can use generics as mentioned above, this falls under the category of making your own class, thought I would mention it seperately too though.

dann.dev
  • 2,406
  • 3
  • 20
  • 32