wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes Storing objects in hashmap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Storing objects in hashmap" Watch "Storing objects in hashmap" New topic
Author

Storing objects in hashmap

Rajendra Prakash
Ranch Hand

Joined: Sep 10, 2009
Posts: 293
The following code used to store and retrieve values in hashmap
HashMap<Integer,String>hmap = new HashMap<Integer,String>();
hmap.put(5,"prak");
hmap.put(1," sachin");

hmap.put(4,"raja");
hmap.put(4,"raja");
Iterator itr= hmap.entrySet().iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
Give me idea for this situation. I need to store objects(long empid,String name, int salary, String Designation)in
hashmap , use empid as key for all the objects.
Rahul Nair
Ranch Hand

Joined: Dec 01, 2007
Posts: 138

Hi,

You can also store the Model Class/Form Bean object to the HashMap, and as use that object's property as a key in HashMap.

Please let me know, if you have any issue.
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 492

So just create a HashMap and make the key the empid field and the value the entire object.

Hunter


"If the facts don't fit the theory, get new facts" --Albert Einstein
Fred Muhlenberg
Ranch Hand

Joined: Jan 08, 2008
Posts: 39
When you store User defined objects in a hashmap (or any collection for that matter), you need to implement the equals() and hashMap() methods. the default implementations of these methods (from java.lang.Object) is generally not sufficient

-Fred.
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Fred Muhlenberg wrote:When you store User defined objects in a hashmap (or any collection for that matter), you need to implement the equals() and hashMap() methods. the default implementations of these methods (from java.lang.Object) is generally not sufficient


This is absolutely true of any objects used as keys in a HashMap; the "value" half of the key/value pair doesn't actually benefit from having these methods. They're important, though, if you want to store the values in a List or Set and be free to use all of the methods of those interfaces.


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Storing objects in hashmap