Hello. I need find a way to retrieve data members from an object. The object is stored as a value in a hash map. Is this even possible?
I've seen examples online which store the <key, value> in the form hm.put(someKey, "someValue") both of which are objects of course, but I've never seen objects which contain data members been put as values in a hashmap.
My question is: how do I get the data members from the object that is stored as a value in the hash map?
name = "john doe";
age = 99;
public Person(String Name, int Age)
name = Name;
age = Age;
public static void main(String args)
Person myPerson = new Person();
HashMap myMap = new HashMap();
myMap.put("1", myPerson); //is this valid?
Set set = myMap.entrySet();
Iterator iter = set.iterator();
Map.Entry hashMap = (Map.Entry)iter.next();
System.out.println(hashMap.getKey() + ". " + hashMap.getValue());
If you're using Java 1.5 or higher, then you should use a generic HashMap<Person> not a plain HashMap as well as a generic Set and Iterator. Then the object returned by the iterator will be a Person object. Otherwise you'll need to cast the object returned as a Person object.
You need to parameterize the HashMap (Generics).
Then, to get a value:
HashMap<Integer,Person> myMap = new HashMap<Integer,Person>;
Person p = myMap.get(1);
Ah, I got it! Thanks a whole lot. :)
What the "H" was I thinking, HashMap<Person>? To the OP, sorry for the misdirection.
Originally Posted by Fubarable