Returning String[] from a method
I want to return two values from a method stored in an array. How can I do it?
For example: The method 开发者_如何学Pythonneeds to return"un"
and "pwd"
.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;
}
Have you tried:
public String[] getLogin() {
String[] names = new String[]{"uname", "passwd"};
return names;
}
It's just like retuning any other object.
If you know how to return any object you would know how to return an array. There is no difference.
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; }
精彩评论