Java Collections – hashCode() 和 equals() – 如何在 Java 中覆盖 equals() 和 hashcode() 方法?
已发表: 2018-08-08
Java 中的equals()
和hashCode()
是在 Object 类和部分或核心 Java 库中声明的两个基本方法。
如果您在 Java 中有以下任何问题,那么您来对地方了。
- Java 实践 -> 实现 equals
- override – 在 Java 中覆盖 equals 和 hashCode
- 如何在java中覆盖equals()方法
- 如何在java中覆盖hashCode()方法
- 如何在 Java 中覆盖 equals 和 hashCode 方法
- 如何以及为什么在 Java 中重写 equals 方法
- 如果覆盖 equals(),为什么总是覆盖 hashcode()?
让我们看一个简单的例子来了解第一个Reference Equality
和Logical Equality
。 相等运算符 (==) 将两个字符串的引用(内存中的地址)作为两个不同的数字进行比较——这称为Reference equality
。
Logical equality
比较对象的数据而不是引用的值。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com . crunchify . tutorials ; /** * @author Crunchify.com */ public class CrunchifyLogicalVsReferenceEqality { public static void main ( String [ ] args ) { String strA = new String ( "eBay" ) ; String strB = new String ( "eBay" ) ; String strC = new String ( "Paypal" ) ; // Create a String reference and assign an existing String's reference to it // so that both references point to the same String object in memory. String strD = strA ; // Print out the results of various equality checks // Reference Equality System . out . println ( "Reference Equality Result:" ) ; System . out . println ( strA == strB ) ; System . out . println ( strA == strC ) ; System . out . println ( strA == strD ) ; // Logical Equality System . out . println ( "\nLogical Equality Result:" ) ; System . out . println ( strA . equals ( strB ) ) ; System . out . println ( strA . equals ( strC ) ) ; System . out . println ( strA . equals ( strD ) ) ; } } |
输出:
1 2 3 4 5 6 7 8 9 |
Reference Equality Result : false false true Logical Equality Result : true false true |
hashCode和equals密切相关:
- 如果您覆盖equals ,则必须覆盖hashCode 。
- hashCode必须为相等的对象生成相等的值。
- equals和hashCode必须依赖于
same set of significant fields
。 您必须在这两种方法中使用相同的字段集。 您不需要使用所有字段。 例如,一个依赖于其他的计算字段很可能应该从equals
和hashCode
中省略。
实现equals时,根据类型对字段进行不同的比较:
- 对象字段,包括集合:使用equals
- 类型安全枚举:使用equals或== (在这种情况下,它们等同于相同的东西)
- 可能为空的对象字段:同时使用==和equals
- 数组字段:使用
Arrays.equals
- float或double以外的原始字段:使用==
-
float
: 转换为int使用Float.floatToIntBits ,
然后使用== -
double
:使用Double.doubleToLongBits
转换为long ,然后使用==
实现hashCode :
- 如果一个类覆盖了equals ,它必须覆盖hashCode
- 当它们都被覆盖时, equals和hashCode必须使用相同的字段集
- 如果两个对象相等,那么它们的hashCode值也必须相等
- 如果对象是不可变的,则hashCode是缓存和延迟初始化的候选对象
hashCode为对象提供唯一标识符是一种流行的误解。 它不是。
按照一般约定,Java 中的equals()
方法必须是自反的、对称的、传递的、一致的,并且任何非空引用都必须返回 false。 换句话说,对于 a、b 和 c 的任意值,以下测试必须始终通过:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
/ reflexive property assertTrue ( a . equals ( a ) ) ; // symmetric property assertTrue ( a . equals ( b ) == b . equals ( a ) ) ; // transitive property if ( a . equals ( b ) && b.equals(c) ) { assertTrue( a.equals(c) ); } // consistency property assertTrue ( a . equals ( b ) == a . equals ( b ) ) ; // non-null property assertFalse ( a . equals ( null ) ) ; |
对于最佳实践,请使用以下步骤来实现您的 equals() 方法:
- 使用 this == that 来检查引用相等
- 使用
instanceof
测试正确的参数类型 - 将参数转换为正确的类型
- 比较重要字段是否相等
这是一个完整的例子。
CrunchifyImplementEqualsHashCode.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
package crunchify . com . tutorials ; /** * * @author Crunchify.com * How to Override equals() method in Java? * How to Override hasCode() method in Java? * version:1.2 * */ public class CrunchifyImplementEqualsHashCode { public static void main ( String [ ] args ) { CrunchifyImplementEqualsHashCode crunchifyTest = new CrunchifyImplementEqualsHashCode ( ) ; Crunchify one = new Crunchify ( 1 ) ; Crunchify two = new Crunchify ( 1 ) ; crunchifyTest . test1 ( one , two ) ; Crunchify three = new Crunchify ( 1 ) ; Crunchify four = new Crunchify ( 2 ) ; crunchifyTest . test2 ( three , four ) ; } public void test1 ( Crunchify one , Crunchify two ) { if ( one . equals ( two ) ) { System . out . println ( "Test1: One and Two are equal" ) ; } else { System . out . println ( "Test1: One and Two are not equal" ) ; } } public void test2 ( Crunchify three , Crunchify four ) { if ( three . equals ( four ) ) { System . out . println ( "Test2: Three and Four are equal" ) ; } else { System . out . println ( "Test2: Three and Four are not equal" ) ; } } } class Crunchify { private int value ; Crunchify ( int val ) { value = val ; } public int getValue ( ) { return value ; } // The method does override or implement a method declared in a supertype. @Override public boolean equals ( Object o ) { // null check if ( o == null ) { return false ; } // this instance check if ( this == o ) { return true ; } // instanceof Check and actual value check if ( ( o instanceof Crunchify ) && (((Crunchify) o).getValue() == this.value)) { return true; } else { return false ; } } @Override public int hashCode ( ) { int result = 0 ; result = ( int ) ( value / 11 ) ; return result ; } } |
Eclipse 控制台输出:
1 2 |
Test1 : One and Two are equal Test2 : Three and Four are not equal |