File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Putting object in HashMap

 
Rizwan Qadri
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 10336
Eclipse IDE Hibernate Java
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
Rizwan Qadri
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 15150
31
Android IntelliJ IDE Java Scala Spring
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rizwan Qadri
Ranch Hand
Posts: 40
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jesper
 
Jan van Mansum
Ranch Hand
Posts: 74
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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

 
I agree. Here's the link: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic