java - 在 HashSet 中调用 System.out.println() 方法的 hashCode 方法

标签 java hashcode

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的原因

  1. 用于在将 Employee 插入到 HashSet

    时查找哈希值
  2. 当您打印集合时,它会调用默认 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/

相关文章:

java - 跟踪 fragment 生命周期,如 Application.ActivityLifecycleCallbacks

java - 为什么这个涉及通配符的赋值在 Java 中是合法的?

java - 需要帮助编写 hashcode 和 equals 方法吗?

c# - IEquatable 的类实现,用作字典中的键

java - String 与其他类对象的 hashCode

java - 为什么 Collections 类包含独立(静态)方法,而不是将它们添加到 List 接口(interface)中?

java - 将 Java 可执行文件(使用 launch4j)固定到 Windows 7 任务栏

java - 一个在某个网站上搜索的java程序

java - 如何制作高效的hashCode?

java hashCode() 函数用于引用变量和对象