class MapTask {
  public static void main(String[] args) {
      Map<KeyClass, Object> map = new HashMap<>();
      KeyClass key = new KeyClass();
      Object value = new Object();
      map.put(key, value);
      map.get(key); // this line should return null     

class KeyClass {

  //class fields


The key is present and the value is not null does it relate to implementing equals() method?

  • 1
    Hi Vlad, If you are working in Java, this is the wrong place to ask.
    – Keith C
    Feb 12 at 10:06
  • Why would you expect to return null, having set a value?
    – Phil W
    Feb 12 at 10:20
  • When you do this: Object value = new Object(); you have initialized an object which has a memory address. Thus when you do map.get(key) you get the instance of the object. Feb 12 at 10:32

1 Answer 1


When using custom classes to define keys, you need both an equals() method and a hashCode() method in order to ensure that the key can be found. The latter identifies the correct "bucket" in which to find the key, and the former is used to ensure that the two objects are indeed equal.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .