• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Putting object in HashMap

 
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Bartender
Posts: 10336
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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()));

}
}
 
Java Cowboy
Posts: 16084
88
Android Scala IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Jesper
 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic