user12174294
user12174294

Reputation:

Does changing hashCode() work if I use a string as a key to the object?

I've been reading about changing hashCode() function in java.
There's one thing I don't really understand: If I have a class Person, and store a HashMap in a class like:
Map<String, Person> map = new HashMap<>(); does the defined hashCode() function do anything? It's just that from what I understand, it would be using the String's hashCode, instead of Person's HashCode() correct?
So if I have this class

public class Person {
    private int age;
    private String name;

    public boolean equals {...}

    public int hashCode() {
        return Objects.hash(age, name);
    }
}

And on main I store a Map of these objects like this:

public class Main {
    public static void main (String [] arg) {
        Map <String, Person> pers = new HashMap<>();
        Person p = new Person("Peter", 21); //Imagine I have this constructor
        pers.put(p.getName(), p);
    }
}

Would this use the hashCode() function defined in the Person class?

Upvotes: 1

Views: 176

Answers (3)

Ashish Kathait
Ashish Kathait

Reputation: 216

In your question Map

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

The key which you are using is String and the Person object is the value in your Map. While you put a value in Map, the key's equals and hashcode method will be considered. So in your scenario it will be String class. There is no way in your example that Person class's equals and hashcode method will be used.

Incase you want to use Person class's hashcode and equals method while putting value in the Map you will have to keep Person as the key in your map. For Example :

Map<Person,SOME_CLASS>[this is only for representational purpose]

Upvotes: 0

Mureinik
Mureinik

Reputation: 310983

hashCode is used on the map's key, not its value. In this case, the key is a String, so nothing would call Person's hashCode, which is the value.

Upvotes: 2

Manish Khandelwal
Manish Khandelwal

Reputation: 2310

Hashcode function comes in picture for the object that is to be used as key in hashmap. In the example which you gave, String class hashcode fuction will be used. Person class hashcode will come in picture when it is used as a key in hashmap.

Upvotes: 1

Related Questions