简体   繁体   中英

Overriding equals method not working on using object as key in hashmap?

I have Overridden equals method of Person class comparing the name attribute of class and if they are equal returning back true from equals method.

When i am creating the instance of Person object and using it as key in hashmap, while retrieving using a new object with same name i am not able to retrieve back the associated value from hashMap.

Below is my

import java.util.HashMap;

import java.util.Map;

public class ToStringTest {

public static void main(String[] args) {

    Person person = new Person("Jack", "California");
    Map<Person,String> personsMap = new HashMap<>();
    personsMap.put(person,"MyCar");
   Person otherPerson = new Person("Jack", "California");
    System.out.println(personsMap.get(otherPerson));
}

}

class Person {

String name;
String city;

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

@Override
public String toString() {
    return "Name : " + this.name + ", City : " + this.city;
}

@Override
public boolean equals(Object o) {

    Person person = (Person) o;
    if(person.name.equals(this.name)){
        return true;
    }

    return false;
}

}

This is printing null while retrieving from using otherPerson object.

Could someone please explain this behavior.

When you add new person in map personsMap.put(person,"MyCar"); first of all if key is not null the position where the element will be put is determined. It is determined by calling hashcode method for key. There are a few steps after but it doesn't matter for this example.

Since you don't override hashcode() your person and otherPerson will have different hashcode .

The same happens when you try to get value by some key. To find position where the element is, hashcode() will be invoked. But otherPerson has different hashcode and it will lead to position where is no item ( null )

equals() is used when at the same position there are many elements (in list or tree structure). Then to find the right item they will be compared by equals() method

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM