File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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
JavaRanch » Java Forums » Java » Java in General
Bookmark "Putting object in HashMap" Watch "Putting object in HashMap" New topic

Putting object in HashMap

Rizwan Qadri
Ranch Hand

Joined: May 28, 2007
Posts: 40
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

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: 15094

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 8 API documentation
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:
subject: Putting object in HashMap
jQuery in Action, 3rd edition