Results 1 to 5 of 5
Thread: HashMap Help
- 09-12-2010, 09:25 PM #1
Member
- Join Date
- Sep 2010
- Posts
- 2
- Rep Power
- 0
HashMap Help
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.
so basically
My question is: how do I get the data members from the object that is stored as a value in the hash map?Java Code:import java.util.*; public Person { String name; int age; public Person() { 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(); while(iter.hasNext()) { Map.Entry hashMap = (Map.Entry)iter.next(); System.out.println(hashMap.getKey() + ". " + hashMap.getValue()); } } }
ThanksLast edited by digitol97; 09-12-2010 at 09:27 PM.
-
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.
- 09-12-2010, 09:50 PM #3
Senior Member
- Join Date
- Jul 2010
- Posts
- 125
- Rep Power
- 0
You need to parameterize the HashMap (Generics).
Then, to get a value:Java Code:HashMap<Integer,Person> myMap = new HashMap<Integer,Person>;
Java Code:Person p = myMap.get(1);
- 09-12-2010, 09:56 PM #4
Member
- Join Date
- Sep 2010
- Posts
- 2
- Rep Power
- 0
Ah, I got it! Thanks a whole lot. :)
-
Similar Threads
-
Something like HashMap
By BigBear in forum New To JavaReplies: 4Last Post: 03-14-2010, 11:08 AM -
How to create a new HashMap from a HashMap entries of other methods
By pandeyalok in forum Advanced JavaReplies: 7Last Post: 12-08-2009, 07:17 PM -
HashMap Help
By ScaryJello in forum New To JavaReplies: 2Last Post: 04-15-2009, 09:18 AM -
Hashmap - get key according to value
By gtriant in forum New To JavaReplies: 1Last Post: 12-15-2008, 02:29 PM -
hashmap
By tOpach in forum New To JavaReplies: 2Last Post: 09-24-2008, 12:55 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks