Perface

  In the former chapter, I talk about topics about hashCode, And I will continue to finish the introduction to hashCode(). In this chapter, I will recommend several ways to overrwrite hashCode()  to facilitate our work

Recommended by the author of "Effective Java"

  Ideally, a hash function should distribute any reasonable collection of unequal instances uniformly across all possible hash values. Here is a simple recipe:
    1.  Store some constant nonzero value, say, 17, in an int variable called result.
    2.  For each significant field f in your object (each field taken into account by the equals method, that is), do the following:
        a.  Compute an int hash code c for the field:
            i.   If the field is a boolean, compute (f ? 1 : 0).
            ii.  If the field is a bytecharshort, or int, compute (int) f.
            iii. If the field is a long, compute (int) (f ^ (f >>> 32)).
            iv. If the field is a float, compute Float.floatToIntBits(f).
            v.  If the field is a double, compute Double.doubleToLongBits(f), and then hash the resulting long as in step 2.a.iii.
            vi. If the field is an object reference and this class’s equals method compares the field by recursively invoking equals, recursively invoke hashCode on the field. If a more complex comparison is required, compute a “canonical representation” for this field and invoke hashCode on the canonical representation. If the value of the field is null, return 0.
            vii. If the field is an array, treat it as if each element were a separate field. If every element in an array field is significant, you can use one of theArrays.hashCode methods.
        b.  Combine the hash code c computed in step 1) into result as follows:
                result = 31 * result + c;
    3.      Return result.

Overriding hashCode() and equals() using Apache Commons Lang

  Apache commons provide two excellent utility classes for generating hash code and equals methods. Below is its usage:

 import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class Employee
{
private Integer id;
private String firstname;
private String lastName;
private String department;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public int hashCode()
{
final int PRIME = 31;
return new HashCodeBuilder(getId()%2==0?getId()+1:getId(), PRIME).
toHashCode();
}
@Override
public boolean equals(Object o) {
if (o == null)
return false;
if (o == this)
return true;
if (o.getClass() != getClass())
return false;
Employee e = (Employee) o;
return new EqualsBuilder().
append(getId(), e.getId()).
isEquals();
}
}

  In the official doucment of HashCodeBuilder, it describes as follow:

  This class enables a good hashCode method to be built for any class. It follows the rules laid out in the book Effective Java by Joshua Bloch. Writing a good hashCode method is actually quite difficult. This class aims to simplify the process.

  The following is the approach taken. When appending a data field, the current total is multiplied by the multiplier then a relevant value for that data type is added. For example, if the current hashCode is 17, and the multiplier is 37, then appending the integer 45 will create a hashcode of 674, namely 17 * 37 + 45.

  All relevant fields from the object should be included in the hashCode method. Derived fields may be excluded. In general, any field used in the equals method must be used in the hashCode method.

  To use this class write code as follows:

 public class Person {
String name;
int age;
boolean smoker;
... public int hashCode() {
// you pick a hard-coded, randomly chosen, non-zero, odd number
// ideally different for each class
return new HashCodeBuilder(17, 37).
append(name).
append(age).
append(smoker).
toHashCode();
}
}

Automatically generated by eclipse IDE

  if you are using any code editor, they also must be capable of generating some good structure for you. For example, Eclipse IDE has option under right click on class >> source > Generate hashCode() and equals() … will generate a very good implementation for you.

  

Summary

  In general, it is not common to override the hashCode() method, but if we need to do it in practical work, it will be a troublesome experience. To make our work easier and more efficiently, it is a good idea to follow the recommendations in the chapter. But if you want to achieve a higher performance, you'd better to override the method yourself carefully.

References

  Working with hashCode and equals methods in java

   Apache Commons Lang

Recommend ways to overwrite hashCode() in java的更多相关文章

  1. String的hashcode(java)

    hashCode就是我们所说的散列码,使用hashCode算法可以帮助我们进行高效率的查找,例如HashMap,说hashCode之前,先来看看Object类. Java程序中所有类的直接或间接父类, ...

  2. Java提高篇——equals()与hashCode()方法详解

    java.lang.Object类中有两个非常重要的方法: 1 2 public boolean equals(Object obj) public int hashCode() Object类是类继 ...

  3. 【java基础学习-2--】关于Hashcode()的使用

    摘要 Java中equals()和hashCode()有一个契约: 如果两个对象相等的话,它们的hash code必须相等: 但如果两个对象的hash code相等的话,这两个对象不一定相等; 这个约 ...

  4. Java中hashcode,equals和==

    hashcode方法返回该对象的哈希码值. hashCode()方法可以用来来提高Map里面的搜索效率的,Map会根据不同的hashCode()来放在不同的位置,Map在搜索一个对象的时候先通过has ...

  5. java 覆盖hashCode()深入探讨 代码演示样例

    java 翻盖hashCode()深入探讨 代码演示样例 package org.rui.collection2.hashcode; /** * 覆盖hashcode * 设计HashCode时最重要 ...

  6. JAVA中的各种 哈希码(HashCode) 与 equals方法在HIBERNATE的实际应用[转载]

    1.什么是哈希码(HashCode) 在Java中,哈希码代表对象的特征.例如对象 Java代码 String str1 = “aa”, str1.hashCode= 3104 String str2 ...

  7. JAVA - hashcode与equals作用、关系

      Hashcode的作用 总的来说,Java中的集合(Collection)有两类,一类是List,再有一类是Set.前者集合内的元素是有序的,元素可以重复:后者元素无序,但元素不可重复.      ...

  8. Java equals 和 hashcode 方法

    问题 面试时经常会问起字符串比较相关的问题, 总结一下,大体是如下几个: 1.字符串比较时用的什么方法,内部实现如何? 2.hashcode的作用,以及重写equal方法,为什么要重写hashcode ...

  9. 使用hashCode()和equals()方法 - Java

    在这篇文章中,我将指出我对hashCode()和equals()方法的理解.我将讨论它们的默认实现以及如何正确地覆盖它们.我还将使用Apache Commons包中的实用工具类来实现这些方法. has ...

随机推荐

  1. With语句上下文管理

    在平时工作中总会有这样的任务,它们需要开始前做准备,然后做任务,然后收尾清理....比如读取文件,需要先打开,读取,关闭 这个时候就可以使用with简化代码,很方便 1.没有用with语句 1 2 3 ...

  2. 学习《精通数据科学从线性回归到深度学习》PDF+代码分析

    数据科学内容广泛,涉及到统计分析.机器学习以及计算机科学三方面的知识和技能.学习数据科学,推荐学习<精通数据科学从线性回归到深度学习>. 针对技术书籍,最好的阅读方法是对照每一章的示例代码 ...

  3. 欢迎使用CSDN-markdown编辑器u

    这里写自定义目录标题 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题,有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一 ...

  4. 转载-浅谈Ddos攻击攻击与防御

    EMail: jianxin#80sec.comSite: http://www.80sec.comDate: 2011-2-10From: http://www.80sec.com/ [ 目录 ]一 ...

  5. nginx并发连接控制模块ngx_http_limit_conn_module

    模块: ngx_http_limit_conn_module 作用: 根据定义的key限制并发连接数 配置示例: http { limit_conn_zone $binary_remote_addr ...

  6. 一个MySQL 5.7 分区表性能下降的案例分析

    告知MySQL5.7.18的使用者分区表使用中存在的陷阱,避免在该版本上继续踩坑.同时通过对源码的讲解,升级MySQL5.7.18时分区表性能下降的根本原因,向MySQL源码爱好者展示分区表实现中锁的 ...

  7. 【小程序云开发入门】quickStart

    开发者可以使用云开发开发微信小程序.小游戏,无需搭建服务器,即可使用云端能力. 云开发为开发者提供完整的云端支持,弱化后端和运维概念,无需搭建服务器,使用平台提供的 API 进行核心业务开发,即可实现 ...

  8. Python小白学习之路(十六)—【内置函数一】

    将68个内置函数按照其功能分为了10类,分别是: 数学运算(7个) abs()   divmod()  max()  min()  pow()  round()  sum() 类型转换(24个) bo ...

  9. J02-Java IO流总结二 《概述》

    1  流的概念 流是一个信息的通道,通过通道可以访问通道连接的文件对象. 2  流的分类 根据流中数据的流向,可分为输入流和输出流 输入流:从其他的地方流入到程序内存中的,比如InputStream. ...

  10. 去掉iphone上拨号弹出框

    1.常规的方法可以直接去除默认事件event.preventDefault() 2.使用vue的话可以: <div @click.stop.prevent=</div> //或者 & ...