Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Who calls the equals method of the class while putting the elements into the HashMap?

I am new to Java (very new). I am trying to understand HashMap and the equals method of a class and how it overrides the duplicates. Please see following code:

public class Student {

    Integer StudentId;
    String Name;
    String City;

    public Student(Integer studentId, String name, String city) {
        super();
        StudentId = studentId;
        Name = name;
        City = city;
    }

    public Integer getStudentId() {
        return StudentId;
    }

    public String getName() {
        return Name;
    }

    public String getCity() {
        return City;
    }




    @Override
    public int hashCode() {
        System.out.println("haschode is called for " + this);

        final int prime = 31;
        int result = 1;
        result = prime * result + ((StudentId == null) ? 0 : StudentId.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        System.out.println("equals is called for " + this);

        if (this == obj)
            return true;

        if (obj == null)
            return false;

        if (getClass() != obj.getClass())
            return false;

        Student other = (Student) obj;

        if (StudentId == null) {
            if (other.StudentId != null)
                return false;

        } else if (!StudentId.equals(other.StudentId))
            return false;

        return true;
    } 


    @Override
    public String toString() {
        return "\n Student [StudentId=" + StudentId + ", Name=" + Name + ", City=" + City + "] \n";
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub


         Map<Student, String> myMap = new HashMap<Student, String>();

         myMap.put(new Student(1, "andy", "p"), "Great");     //Line 1
         myMap.put(new Student(2, "sachin", "m"), "Better");
         myMap.put(new Student(3, "dev", "s"), "Good");
         myMap.put(new Student(1, "andy", "p"), "Excellent"); // Line 4

         System.out.println(myMap);


    }

}

Now, the code written in main() calls the equals method only when I write the code to put the same key again i.e. "Line 4" (see my code indentation).

Why is the equals method not called for "Line 2" and "Line 3"?? It should call equals for every put line .... correct?

I am missing some understanding here and am left with questions: (1) Why is every put not calling the equals method to check the equality of class members? (2) Who triggers the call of the Student class equals method?

like image 406
user2746466 Avatar asked Jun 19 '19 13:06

user2746466


People also ask

When equals method is called in HashMap?

equals() method: This method is used to check whether 2 objects are equal or not. This method is provided by the Object class. You can override this in your class to provide your implementation. HashMap uses equals() to compare the key to whether they are equal or not.

How do you call equals method in Java?

In Java terms, they are equal, which is checked with equals : String some = "some string"; String other = "some string"; boolean equal = some. equals(other); Here, equals is true .

Which is called first hashCode or equals?

@Puce No, hashCode is always called first to get the bucket, and then equals is called to check things at that bucket.

What is the purpose of the equals () method?

Definition and Usage. The equals() method compares two strings, and returns true if the strings are equal, and false if not.


1 Answers

It should call equals for every put line .... correct ?

No. A HashMap will call equals only after it encounters a hash collision between an existing key and the one given in put.

Rephrased, it calls hashCode first to determine which "hash bucket" to put the key into, and if there are already keys inside the target bucket, it then uses equals to compare the keys in the bucket for equality.

Since the value of Student.hashCode() is based on ID alone, during insertion, the map only needs to call equals when it encounters a Student key with the same ID as what is being inserted. If no existing keys have the same hashCode as the one being inserted, there is no need to call equals.

This makes HashMap very efficient during insertion. This is also why there is a contract between hashCode and equals: If two objects are equal as defined by equals, they must also have the same hashCode (but not necessarily vice-versa).

like image 191
Zircon Avatar answered Sep 25 '22 00:09

Zircon