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"
.
views:
173answers:
4
+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
2010-01-11 06:19:33
+1: That's the object-oriented way :-).
sleske
2010-01-11 11:29:36
-1 for public, non-final fields.
Tom Hawtin - tackline
2010-01-11 13:10:46
from a strict "java" OOP way, this is the correct way to do this.
PaulP1975
2010-01-11 13:41:11
To appease Tom I've added get/set. Lots more typing, zero% more sense ;)
Will
2010-01-11 13:58:07
@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
2010-01-11 14:04:10
+2
A:
If you know how to return any object you would know how to return an array. There is no difference.
fastcodejava
2010-01-11 06:21:23
+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
2010-01-11 06:21:43
+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
2010-01-11 11:25:42
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
2010-01-11 11:29:02
sleske, agreed... the custom class is better. however, you could handle the key issue by defining static (final) constants.
PaulP1975
2010-01-11 13:42:36