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".
-
Not to nitpick but in the OO world, object functions are called methods. Jave does not have functions per se, as all methods must be in the scope of some class / object.D.C.– D.C.2010-01-11 06:24:32 +00:00Commented Jan 11, 2010 at 6:24
Add a comment
|
4 Answers
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;
}
3 Comments
PaulP1975
from a strict "java" OOP way, this is the correct way to do this.
Will
To appease Tom I've added get/set. Lots more typing, zero% more sense ;)
Joachim Sauer
@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.
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;
}
2 Comments
sleske
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.
PaulP1975
sleske, agreed... the custom class is better. however, you could handle the key issue by defining static (final) constants.