views:

173

answers:

4

I want to return two values from a method stored in an array. How can I do it?
For example: The method needs to return "un" and "pwd".

+8  A: 

A tidy and Javaesque way to return multiple values is to create an object to return them in, e.g.

public class Whatever {
   public String getUn() { return m_un; }
   public String setUn(String un) { m_un = un; }
   public String getPwd() { return m_pwd; }
   public String setPwd(String pwd) { m_pwd = pwd; }
};

public Whatever getWhatever() {
   Whatever ret = new Whatever();
   ...
   ret.setPwd(...);
   ret.setUn(...);
   ...
   return ret;
}
Will
+1: That's the object-oriented way :-).
sleske
-1 for public, non-final fields.
Tom Hawtin - tackline
from a strict "java" OOP way, this is the correct way to do this.
PaulP1975
To appease Tom I've added get/set. Lots more typing, zero% more sense ;)
Will
@Will: final public fields, initialized in a constructor would be ok as well: a tiny amount more typing, clear intent, no possibility of mis-use.
Joachim Sauer
+2  A: 

If you know how to return any object you would know how to return an array. There is no difference.

fastcodejava
Also: there is no spoon
Adriaan Koster
+5  A: 

Have you tried:

public String[] getLogin() {
   String[] names = new String[]{"uname", "passwd"};
   return names;
}

It's just like retuning any other object.

zipcodeman
+1  A: 

A HashMap works well for this too. That way you don't have to write a special class.

public Map<String,String> getLogin() {
   Map<String,String> map = new HashMap<String,String>();
   map.put("item1", "uname");
   map.put("item2", "passwd");
   return map;
}
dhg
Yes, that is possible, but using Hashmaps for returning multiple values can quickly get hard to follow ("Now under what key did I put value xyz?"). It's usually better to create a small custom class to wrap the values, as suggested by Will.
sleske
sleske, agreed... the custom class is better. however, you could handle the key issue by defining static (final) constants.
PaulP1975