Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

return multiple values from a method

 
Phoebe Song
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
What's the correct syntax for returning multiple values from a method?
for example I want a method return int x and int y. Is this correct?

public int amethod
{
some codes here


return x, y;
}

Thanks for any help.
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You cannot return multiple values from a method. If you have more than one value you want returned, you could encapsulate them into an object and return a reference to the object.
 
Dana Bothner-By
Ranch Hand
Posts: 37
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

If you want to return x and y values, it sounds like a point in space to Muggins.
 
Phoebe Song
Ranch Hand
Posts: 58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I see... Thank you.
 
Prasanna Chennupati
Ranch Hand
Posts: 38
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to return multiple values from a method,wrap those values in an array or return them as a collection.

Here is an example

public List someMethod()
{

//do some manipulation.
List list = new ArrayList();
list.add(x);
list.add(y);
//add more values as you need.
return list;
}

when you want to return multiple values,returning them in the form of collection classes is a good idea.You might use Array too.
 
Paul Clapham
Sheriff
Posts: 21107
32
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or write more than one method, each of which returns one of the values.
 
Tony Morris
Ranch Hand
Posts: 1608
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or put the code that uses the values you get back into the class you got them from. If you follow the multiple gets with a calculation and a set ... well, there's your sign.

Could maybe be
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic