Question

import java.util.HashSet;
import java.util.Set;

   class Employee {
    @Override
      public int hashCode() {
    System.out.println("Hash");
    return super.hashCode();
    }

}

 public class Test2 {

public static void main(String[] args) {
    Set<Employee>set= new HashSet<>();
    Employee employee = new Employee();
    set.add(employee);
    System.out.println(set);// if we comment this "Hash" will be printed once
}
 }

Above code calls hashCode method 2 times if we print set. Why hashcode method is called on System.out.println()?

Was it helpful?

Solution 2

See this. In short, the default toString() function calls hashCode() and uses a hexadecimal representation of the hash as part of the String.

OTHER TIPS

Find the following reason for printing Hash two times

  1. For finding the hash value when you insert the Employee into the HashSet

  2. When you print the set, it's calls the hashCode() method inside the default toString() method from Object class.

The default toString() method from Object class API docs says

The toString() method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

The first call to hashCode() is executed when adding an Employee to your set variable, as it's needed in order to calculate which bucket to put it in.

The second call is a bit sneaker. Any Collection's default toString() is a coma-delimited concatination of all its elements toString()s enclosed by square brackets (e.g., [object1, object2]). Any object's default toString(), if you don't override it is getClass().getName() + "@" + Integer.toHexString(hashCode()). Here, since you don't override Employee's toString(), it's called again when you print set.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top