What will be the result of the following code execution?

import java.util.*;

class Employee {
    private String name;

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

    public String toString() {
        return name;
    }

    public boolean equals(Object obj) {
        HashCodeTest.count++;

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

        Employee emp = (Employee) obj;
        if (this.name == emp.name) {
            return true;
        }
        return false;
    }

    public int hashCode(){
        return name.hashCode();
    }
}

public class HashCodeTest {
    static int count = 0;

    public static void main(String[] args) {

        Map employees = new HashMap();

        employees.put(new Employee("Joe"), new Integer("1"));
        employees.put(new Employee("Chandler"), new Integer("2"));
        employees.put(new Employee("Chandler"), new Integer("2"));
        employees.put(new Employee("Ross"), new Integer("3"));
        
        Iterator iterator = employees.keySet().iterator();

        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }

        System.out.println(count);
    }
}

P.S. For experts - hashtags of the lines "Joe", "Chandler" и "Ross" are different.
Explanation
If adding a pair key-value to Map it turns out that such a key already exists there, a new value is put into comformity with it.
In the Employee class equals () method is implemented in a way that two objects are considered equal if they contain the same reference to the string name (this.name == emp.name). Therefore, from two objects-keys containig the reference to the constant-string "Chandler" only one of them remains in Map. Count field is used to count the number of calls of Employee.equals (). When working with HashMap equals () method is called relatively seldom, for example, when the hash-code of a newly added key matches the hash-code of the previously added key - to reliably verify that it is the same object (equality of hash-codes does not guarantee equality of objects). In this example, it happens only once, during the second addition of Chandler.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback