java - 为什么不同 boolean 实例的哈希码总是相同的?

标签 java boolean hashcode

在下面的代码中,哈希码总是相同的。为什么会这样?

代码:

public class BooleanClass {

    public static void main(String[] args) {
        Boolean b1 = new Boolean(true);
        Boolean b2 = new Boolean(false);
        Boolean b3 = new Boolean(true);
        Boolean b4 = new Boolean(false);
        Boolean b5 = new Boolean(false);
        Boolean b6 = new Boolean(true);

        System.out.println(b1.hashCode());
        System.out.println(b2.hashCode());
        System.out.println(b3.hashCode());
        System.out.println(b4.hashCode());
        System.out.println(b5.hashCode());
        System.out.println(b6.hashCode());
    }
}

输出:

1231
1237
1231
1237
1237
1231

总是打印相同的数字 12311237。有什么原因吗?

最佳答案

The JavaDoc Boolean.hashCode() 方法说:

Returns the integer 1231 if this object represents true; returns the integer 1237 if this object represents false.

关于java - 为什么不同 boolean 实例的哈希码总是相同的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22683634/

相关文章:

java - Java 8 中默认的 Full GC 间隔是多少

perl - 如何在 Perl 中使用 boolean 变量?

java - 如何创建具有两个键(键对、值)的 HashMap?

java - hashcode() 和 equals() 方法

.net - 字符串对象的 GetHashCode() 值是否唯一?

java - 获取绝对 java.nio.Path

java - 通用方法 - "private <T> boolean (T[], T[])"

java - Spring Boot 处理 SizeLimitExceededException

c++ - 在嵌套的 if 语句中使用函数来触发 Action

objective-c - @property 问题 - Objective C