方法定义
public int hashCode()
- 修饰符:
public
- 返回值:
int
类型的哈希码 - 功能:返回该
Integer
对象的哈希码值
核心功能说明
特性 | 说明 |
---|---|
哈希计算规则 | 直接返回 Integer 对象包含的整数值 |
等值一致性 | 若两个 Integer 对象值相等,则 hashCode() 返回值必定相同 |
重写原则 | 重写 Object.hashCode() 确保与 equals() 行为一致 |
性能特点 | O(1) 时间复杂度,无复杂计算 |
方法源码分析
public int hashCode() {
return Integer.hashCode(value);
}
// 静态方法实现
public static int hashCode(int value) {
return value;
}
源码验证:直接返回原始
int
值,无任何转换或计算
详细示例代码
基础用法
Integer num = 42;
int hash = num.hashCode(); // 返回42
System.out.println(hash); // 输出: 42
等值对象验证
Integer a = 1000;
Integer b = 1000;
System.out.println(a.equals(b)); // true
System.out.println(a.hashCode() == b.hashCode()); // true
集合应用
Map<Integer, String> colorMap = new HashMap<>();
colorMap.put(0xFF0000, "Red"); // 键的hashCode=16711680
colorMap.put(0x00FF00, "Green"); // 键的hashCode=65280
System.out.println(colorMap.get(0xFF0000)); // 输出"Red"
使用技巧
自定义对象哈希优化
class Point { private int x, y; @Override public int hashCode() { return 31 * x + y; // 使用整数哈希组合 } }
快速哈希生成
// 生成基于多个整数的复合哈希 int hash = Objects.hash(intVal1, intVal2, intVal3);
枚举值处理
enum Status { ACTIVE(1), INACTIVE(0); private final int code; Status(int code) { this.code = code; } @Override public int hashCode() { return code; } }
常见错误与规避
混淆实例与静态方法
// 错误:静态调用实例方法 int hash = Integer.hashCode(42); // 编译错误 // 正确:实例方法调用 Integer num = 42; int hash = num.hashCode();
空指针异常
Integer nullInt = null; int hash = nullInt.hashCode(); // 抛出 NullPointerException // 修复:空安全处理 int safeHash = (nullInt != null) ? nullInt.hashCode() : 0;
哈希冲突误解
// 错误:认为不同整数的哈希值必不同 System.out.println(1000.hashCode() == 1000); // true System.out.println(1001.hashCode() == 1000); // false // 但:-1 和 4294967295 在32位系统可能有相同哈希
注意事项
哈希碰撞特性
- 不同整数 必然 返回不同哈希值(因直接返回值本身)
- 此特性仅适用于
Integer
,其他类型不保证
缓存范围影响
Integer a = 127; // 缓存对象 Integer b = 127; // 同一对象 System.out.println(a == b); // true Integer c = 128; // 新对象 Integer d = 128; // 新对象 System.out.println(c == d); // false // 但 hashCode 仍相同:c.hashCode() == d.hashCode()
无符号整型处理
// 处理无符号值需显式转换 long unsigned = Integer.toUnsignedLong(-1); int hash = Long.hashCode(unsigned); // 返回-1的哈希
最佳实践与性能优化
集合键选择策略
graph TD A[选择集合键类型] --> B{需精确匹配?} B -->|是| C[使用Integer] B -->|否| D[考虑String或其他]
高频访问优化
// 低效:反复计算相同哈希值 for (int i = 0; i < 1e6; i++) { map.get(key.hashCode() % buckets); } // 高效:预计算哈希 final int precomputedHash = key.hashCode(); for (int i = 0; i < 1e6; i++) { map.get(precomputedHash % buckets); }
哈希容器初始化
// 根据数据范围设置初始容量 int maxValue = 10000; Map<Integer, String> map = new HashMap<>(maxValue * 4/3 + 1);
关键总结
场景 | 推荐方案 | 原理说明 |
---|---|---|
基本哈希获取 | 直接调用 intValue() 或 hashCode() |
两者返回值相同 |
复合对象哈希 | 使用 Objects.hash() 组合多个值 |
自动处理空值和类型组合 |
高频哈希访问 | 预计算并复用哈希值 | 避免重复计算开销 |
无符号整数处理 | 转换为 long 后调用 Long.hashCode() |
正确处理32位以上无符号值 |
空安全访问 | 三元运算符处理空对象 | 防止 NullPointerException |
自定义类实现 | 使用整数字段参与哈希计算 | 符合 hashCode /equals 约定 |