0

How does containsKey really work? I know that if I do this:

 Map<String, Integer> map = new HashMap<>();
 map.put("user1", 1);
 map.put("user2", 2);
 map.put("user3", 3);

 System.out.println(map.containsKey("user1")); // true

containsKey returns true

but If I do this:

Map<Person, Integer> table = new HashMap<>();
table.put(new Person("Steve"), 33);
table.put(new Person("Mark"), 29);

System.out.println(table.containsKey(new Person("Steve"))); // false

so why am I getting false even if I have the correct key? How do I check for value of 33 by using its key?

Devmix
  • 1,599
  • 5
  • 36
  • 73
  • 6
    Because your `Person` class doesn't (correctly) implement `hashCode()` and `equals()`. – Andreas Aug 04 '19 at 00:59
  • 1
    Because you haven't implemented `equals()` on your class Java can only check to see if the 2 objects reference the same memory. This explains how equality works in Java https://stackoverflow.com/questions/7520432/what-is-the-difference-between-and-equals-in-java – DCTID Aug 04 '19 at 02:20

2 Answers2

2

Here you are using String as key

Map<String, Integer> map = new HashMap<>();

map.put("user1", 1);

And String class ia implementing HashCode and Equals method and hence it is working as expected.

While you are using Person class object as key or any custom class, you should make sure that you override Hashcode and equals method.

HashMap implemention uses hashCode to find bucket and the uses equals if there are multiple entries present in bucket.

Shiva
  • 1,962
  • 2
  • 13
  • 31
1

When working with maps all the objects that need to be stored in the map should implement equals and hashcode

Here is sample Person class that behaves as you would expect:

class Person {
        private String name;

        public Person(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object obj) {
            if (obj == null || !(obj instanceof Person)) {
                return false;
            }

            Person other = (Person) obj;

            return other.getName().equals(this.name);
        }

        @Override
        public int hashCode() {
            return this.name.hashCode();
        }

    }

HashMap uses equals() to compare whether the keys are equal or not hashCode() is used to calculate the index in which the item should be inserted

Borislav Stoilov
  • 3,247
  • 2
  • 21
  • 46