Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Storing objects in hashmap

 
Rajendra Prakash
Ranch Hand
Posts: 293
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 138
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
Posts: 492
Firefox Browser Linux VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So just create a HashMap and make the key the empid field and the value the entire object.

Hunter
 
Fred Muhlenberg
Ranch Hand
Posts: 39
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic