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
}
}
如果我们打印 set,上面的代码会调用 hashCode 方法 2 次。为什么在 System.out.println() 上调用 hashcode 方法?
最佳答案
找到下面打印两次Hash
的原因
用于在将
时查找哈希值Employee
插入到HashSet
当您打印集合时,它会调用默认
toString()
中的hashCode()
方法。Object
类中的方法。
Object
类 API 文档中的默认 toString()
方法
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())
关于java - 在 HashSet 中调用 System.out.println() 方法的 hashCode 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22294249/