aspose file tools*
The moose likes Java in General and the fly likes Putting object in HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Putting object in HashMap" Watch "Putting object in HashMap" New topic
Author

Putting object in HashMap

Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Hi,All,
Can we put() an object as a key in HashMap? I am doing this but, doing get(key) gives me null value. Thanks
Paul Sturrock
Bartender

Joined: Apr 14, 2004
Posts: 10336

Yes. In fact we must use an Object as a key (though auto-boxing may make it appear otherwise). can you post the code that is giving you a problem?


JavaRanch FAQ HowToAskQuestionsOnJavaRanch
Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Hi, Paul,
this is the code:

import java.util.*;
class Collection1
{
static int i=9;
public static void main(String[] args)
{
Map mp=new HashMap();
mp.put(new Collection1(),i);

Collection1 cl=new Collection1();

System.out.println("Hello World!"+mp.get(new Collection1()));

}
}
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 13869
    
  10

You must implement an equals() and a hashCode() method in your class Collection1 to make this work properly.

See the API documentation of the equals() and hashCode() methods in class Objects for information on how to implement those methods.


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
Thanks Jesper
Jan van Mansum
Ranch Hand

Joined: Oct 19, 2007
Posts: 74
To get the same value back from a map you must use a key object that is "equal" to the one you used to put it in the map



SCJP 1.4, SCWCD 1.4
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Putting object in HashMap
 
Similar Threads
HashMap Doubt
Object identifier
Putting object in HashMap
In JSP : Retrieve data from a hashmap
HashMap access problem