Java: rewrite eqJava: override equals () and hashCode () uals () and hashCode ()

2010-10-24  来源:本站原创  分类:Java  人气:145 

Copyright: original works, for permission to reproduce, reprint, please be sure to hyperlink to the original source of the article indicated, author information and this statement. Otherwise held liable. http://zhangjunhd.blog.51cto.com/113473/71571

The following summary from the "Effective Java".

1. When you need to override equals ()

When a class has its own unique "logical equal" concept (as opposed to the concept of object identity.)

2. Design equals ()

[1] using the instanceof operator to check the "argument of whether the correct type."

[2] For each class a "key field", to check the arguments in the current object in the domain and the corresponding field values.

[2.1] for non-float and double primitive type type field, use the == comparison;

[2.2] for object reference domain, recursive calls equals method;

[2.3] for float field, use the Float. FloatToIntBits (afloat) is converted to int, then use the == comparison;

[2.4] for the double domains, use the Double. DoubleToLongBits (adouble) converted to int, then use the == comparison;

[2.5] for the array of domain, call Arrays.equals method.

3. When override equals (), you always want to rewrite the hashCode ()

According to a class equals method (rewritten), there may be two distinct instances are equal in terms of logic, but, according Object.hashCode methods, they are only two objects. Therefore, a violation of "equal objects must have equal hash codes."

4. Design hashCode ()

[1] to a non-zero constant value, such as 17, the result stored in the int variable;

[2] For each of the key objects in the domain f (equals methods that consider each domain):

[2.1] boolean type, calculated (f? 0: 1);

[2.2] byte, char, short type, calculate (int);

[2.3] long type, calculate (int) (f ^ (f>>> 32));

[2.4] float-type, calculated Float. FloatToIntBits (afloat);

[2.5] double type, calculated Double. DoubleToLongBits (adouble) to get a long, then the implementation of [2.3];

[2.6] object reference, recursively call its hashCode method;

[2.7] array domain, each element of which is called its hashCode method.

[3] to calculate the hash code above saved to int variable c, then run result = 37 * result + c;

[4] return result.

5. Example

Following the design of the class to follow the above principles, the class overrides the equals () and hashCode ().

package com.zj.unit;

import java.util.Arrays;

public class Unit {

private short ashort;

private char achar;

private byte abyte;

private boolean abool;

private long along;

private float afloat;

private double adouble;

private Unit aObject;

private int [] ints;

private Unit [] units;

public boolean equals (Object o) {

if (! (o instanceof Unit))

return false;

Unit unit = (Unit) o;

return unit.ashort == ashort

& & Unit.achar == achar

& & Unit.abyte == abyte

& & Unit.abool == abool

& & Unit.along == along

& & Float. FloatToIntBits (unit.afloat) == Float

. FloatToIntBits (afloat)

& & Double. DoubleToLongBits (unit.adouble) == Double

. DoubleToLongBits (adouble)

& & Unit.aObject.equals (aObject)

& & EqualsInts (unit.ints)

& & EqualsUnits (unit.units);

}

private boolean equalsInts (int [] aints) {

return Arrays. equals (ints, aints);

}

private boolean equalsUnits (Unit [] aUnits) {

return Arrays. equals (units, aUnits);

}

public int hashCode () {

int result = 17;

result = 37 * result + (int) ashort;

result = 37 * result + (int) achar;

result = 37 * result + (int) abyte;

result = 37 * result + (abool? 0: 1);

result = 37 * result + (int) (along ^ (along>>> 32));

result = 37 * result + Float. floatToIntBits (afloat);

long tolong = Double. doubleToLongBits (adouble);

result = 37 * result + (int) (tolong ^ (tolong>>> 32));

result = 37 * result + aObject.hashCode ();

result = 37 * result + intsHashCode (ints);

result = 37 * result + unitsHashCode (units);

return result;

}

private int intsHashCode (int [] aints) {

int result = 17;

for (int i = 0; i <aints.length; i + +)

result = 37 * result + aints [i];

return result;

}

private int unitsHashCode (Unit [] aUnits) {

int result = 17;

for (int i = 0; i <aUnits.length; i + +)

result = 37 * result + aUnits [i]. hashCode ();

return result;

}

}

Copyright: original works, for permission to reproduce, reprint, please be sure to hyperlink to the original source of the article indicated, author information and this statement. Otherwise held liable. http://zhangjunhd.blog.51cto.com/113473/71571

The following summary from the "Effective Java".

1. When you need to override equals ()

When a class has its own unique "logical equal" concept (as opposed to the concept of object identity.)

2. Design equals ()

[1] using the instanceof operator to check the "argument of whether the correct type."

[2] For each class a "key field", to check the arguments in the current object in the domain and the corresponding field values.

[2.1] for non-float and double primitive type type field, use the == comparison;

[2.2] for object reference domain, recursive calls equals method;

[2.3] for float field, use the Float. FloatToIntBits (afloat) is converted to int, then use the == comparison;

[2.4] for the double domains, use the Double. DoubleToLongBits (adouble) converted to int, then use the == comparison;

[2.5] for the array of domain, call Arrays.equals method.

3. When override equals (), you always want to rewrite the hashCode ()

According to a class equals method (rewritten), there may be two distinct instances are equal in terms of logic, but, according Object.hashCode methods, they are only two objects. Therefore, a violation of "equal objects must have equal hash codes."

4. Design hashCode ()

[1] to a non-zero constant value, such as 17, the result stored in the int variable;

[2] For each of the key objects in the domain f (equals methods that consider each domain):

[2.1] boolean type, calculated (f? 0: 1);

[2.2] byte, char, short type, calculate (int);

[2.3] long type, calculate (int) (f ^ (f>>> 32));

[2.4] float-type, calculated Float. FloatToIntBits (afloat);

[2.5] double type, calculated Double. DoubleToLongBits (adouble) to get a long, then the implementation of [2.3];

[2.6] object reference, recursively call its hashCode method;

[2.7] array domain, each element of which is called its hashCode method.

[3] to calculate the hash code above saved to int variable c, then run result = 37 * result + c;

[4] return result.

5. Example

Following the design of the class to follow the above principles, the class overrides the equals () and hashCode ().

package com.zj.unit;

import java.util.Arrays;

public class Unit {

private short ashort;

private char achar;

private byte abyte;

private boolean abool;

private long along;

private float afloat;

private double adouble;

private Unit aObject;

private int [] ints;

private Unit [] units;

hashMap hashcode

  • 03:14
  • View (0)
  • Comments (0)
  • Category: JAVA
  • Related Recommendation
Comments
Comment

相关文章
  • Java: rewrite eqJava: override equals () and hashCode () uals () and hashCode () 2010-10-24

    Copyright: original works, for permission to reproduce, reprint, please be sure to hyperlink to the original source of the article indicated, author information and this statement. Otherwise held liable. http://zhangjunhd.blog.51cto.com/113473/71571

  • Override equals method, override hashCode method why 2010-08-26

    1, the first hashCode () is a method of Object class API, the following instructions: public int hashCode () returns the object's hash code value. Support for the hash table is to provide some advantages, such as, java.util.Hashtable hash table provi

  • Java, the difference between equals and == Xiangjie 2010-03-29

    【Zhuantie - not forgetting the original quote address is recorded, please forgive me】 Value types Value types are stored in the memory stack (hereafter referred to as the stack), while the reference type of a variable on the stack only reference type

  • Java rewrite common method of Object class 2010-09-08

    When we write a class when the class will be on Java.lang.Object rewrite some of the important methods, these methods include: hashCode (), toString (), equals (), finalize (), clone (), wait ( ), notify () / notifyAll () method of the eight. One Equ

  • Java: All of the equals method implementation is wrong [transfer] 2011-04-28

    Fast Translation] [51CTO This paper introduces a rewritten (override) equals method for skills. The use of the technique, even if a subclass of the entity to add a new field (field), there is still equals methods to meet the contract. In "Effective J

  • java 中的==和equals 2012-09-10

    基本数据类型 对于基本数据类型,也称原始数据类型(byte.short.int.long.float.double.boolean.char)之间的比较使用"=="操作符,比较的是它们的值是否相等. 引用数据类型 == 在对引用数据类型之间使用"=="操作符的时候,比较的是它们在内存中的存放地址是否相同 package cn.nevo.equals; public class EqualsTest { public static void main(String[]

  • Java, the difference between equals and the equals sign, feel in a good 2010-03-25

    Transfer from: http://www.javaresearch.org/html/article/46110.htm Summarized in one sentence: == to compare two object references (ie, memory address) is equal, and equals () comparison is the value of two objects (ie, memory address where stored val

  • why在重写equals时还必须重写hashcode方法分享 2015-03-25

    首先我们先来看下String类的源码:可以发现String是重写了Object类的equals方法的,并且也重写了hashcode方法 public boolean equals(Object anObject) { if (this == anObject) { return true; } if (anObject instanceof String) { String anotherString = (String)anObject; int n = count; if (n == ano

  • Java, the difference between equals and == 2010-09-05

    Value types are stored in the memory stack (after the short stack), and a reference type variable is only stored on the stack the address of a reference type variable, and then stored in the heap of its own. == Operator compare the two variables are

  • Java overload和override的区别分析 2013-12-19

    方法的重写(Overriding)和重载(Overloading)是Java多态性的不同表现,想要了解更多请参考本文 方法的重写(Overriding)和重载(Overloading)是Java多态性的不同表现.重写(Overriding)是父类与子类之间多态性的一种表现,而重载(Overloading)是一个类中多态性的一种表现. 如果在子类中定义某方法与其父类有相同的名称和参数,我们说该方法被重写 (Overriding).子类的对象使用这个方法时,将调用子类中的定义,对它而言,父类中的定义

  • java中使用@override作用 2012-04-25

    @override有注释文档的作用,可有可无有点像鸡肋 但它对于编程粗心的人可是个很人性化的功能 如果想重写父类的方法,比如toString()方法的话,在被重载的方法前面加上@Override ,这样编译的时候系统可以帮你检查方法的正确性 如下 @Override public String toString(){...}这是正确的 如果将toString写成tostring @Override public String tostring(){...}编译器可以检测出这种写法是错误的,提醒你

  • JAVA中字符串比较equals()和equalsIgnoreCase()的区别 2014-10-28

    1 使用equals( )方法比较两个字符串是否相等.它具有如下的一般形式: boolean equals(Object str) 这里str是一个用来与调用字符串(String)对象做比较的字符串(String)对象.如果两个字符串具有相同的字符和长度,它返回true,否则返回false.这种比较是区分大小写的. 2 为了执行忽略大小写的比较,可以调用equalsIgnoreCase( )方法.当比较两个字符串时,它会认为A-Z和a-z是一样的.其一般形式如下: boolean equalsI

  • equals the true time, hashcode must be equal 2010-05-03

    equals the true time, hashcode must be equal, this rule was not previously noted, each override equals methods are not considered hahsCode, write here to make a mark. If you override equals, but not modify the hashCode, HashMap, and the like in the u

  • hash function for a sum, and with hashcode (). hashMap relations [Z] 2010-10-12

    Hash functions that had previously been very profound, on the Wang Shan's "Principles of database implementation," when it seems to understand a little bit, but to learn java Time, frequent contact with hashcode (), hashMap these to always think

  • JAVA in the equals () and hashCode () method 2009-11-02

    Quote In the Java language, equals () and hashCode () using the two functions are closely co-ordinated if you are one of their own design, we must design another one. In most cases, these two functions are not considered, the direct use of their defa

  • java in the hashcode () and equals () of the Xiang Jie [change] 2009-07-20

    java in the hashcode () and equals () of the Xiang Jie [change] October 30, 2008 Thursday, 11:23 PM Research this afternoon for a long time hashcode () and equals () method, finally had a little bit to understand, write down and share 1. First of equ

  • JAVA based (a) equals and == and hashCode 2010-06-07

    JAVA based (a) equals and == and hashCode According to excerpts online content Heap (heap) and stack (stack) the difference between heap memory: heapstorage heap storage allocation: heapstorage allocation heap storage management: heap storage managem

  • java in the hashcode () and equals () Wapakhabulo 2010-07-22

    1. First equals () and hashcode () These two methods are inherited from object class in the. equals () method in the object class is defined as follows: public boolean equals (Object obj) ( return (this == obj); ) Obviously, the address of the two ob

  • Of Java, == equals hashcode 2010-07-23

    1. '==' Is used to compare two variables (the basic type and object type) value is equal, if two variables are the basic types, it is very easy to directly compare the value on it. If two variables are the object type, then it is quite the value, but

  • Java in the hashcode () and equals () method Detailed 2010-10-05

    Quoted from http://www.cnjm.net/tech/article4731.html For a long afternoon of hashcode () and equals () method, finally have a little bit to understand, write it down and share (zhaoxudong 2008.10.23 Late 21.36). 1. First equals () and hashcode () of