Monday, April 21, 2008

Return more than one values from a method !!

//returns student first name, last name, age given the ssn
public Map getStudentInfo(String ssn){
String fName = null;
String lName = null;
int age = 0;
Hashtable info = new Hashtable();

//pretend we looked up the information rather than hardcoding it and place
//items in a Hashtable in this case

info.put("FName", "Jean-Luc");
info.put("LName", "Pickard");
info.put("Age", new Integer(52)); //age is of type int; like all primitives, it must be wrapped

//return the object
return info;
}
In the calling method you need to get the items out of the Map and cast to what you needMap stuInfo = getStudentInfo("123-45-6789");
String firstName = (String)stuInfo.get("FName");
String lastName = (String)stuInfo.get("LName");
int stuAge = ((Integer)stuInfo.get("Age")).intValue(); //Get the value of the wrapper object

...

No comments: