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

1
  • @BeauGrantham i want to return different objects Commented Dec 20, 2011 at 22:56

3 Answers 3

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());
Sign up to request clarification or add additional context in comments.

2 Comments

Which one of these solution is better? your's or this: stackoverflow.com/questions/457629/…
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 :)
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.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.