Reputation: 497
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()?
Upvotes: 1
Views: 1474
Reputation: 32478
Find the following reason for printing Hash
two times
For finding the hash value when you insert the Employee
into the HashSet
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())
Upvotes: 3
Reputation: 312086
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
.
Upvotes: 1