2

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".

1
  • 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. Commented Jan 11, 2010 at 6:24

4 Answers 4

8

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

from a strict "java" OOP way, this is the correct way to do this.
To appease Tom I've added get/set. Lots more typing, zero% more sense ;)
@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.
5

Have you tried:

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

It's just like retuning any other object.

Comments

2

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

Comments

1

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

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, agreed... the custom class is better. however, you could handle the key issue by defining static (final) constants.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.