zoukankan      html  css  js  c++  java
  • 重写hashCode()的方法

    重写hashCode()方法的基本规则:

    1、在程序运行过程中,同一个对象多次调用hashCode()方法应该返回相同的值

    2、当两个对象通过equals()方法比较返回true时,这两个对象的hashCode()方法返回的值也应该相等

    3、对象中用作equals()方法比较标准的Field,都应该用来计算hashCode值

    重写hashCode()方法的一般规则:

    1、把对象内每个有意义的Field计算出一个int类型的hashCode值,计算方式如下:

    Field类型 计算方式
    boolean hashCode=(f ? 0 : 1);
    整数类型(byte,short,char,int) hashCode=(int)f;
    long hashCode=(int)(f^(f>>>32))
    float hashCode=Float.floatToIntBits(f);
    double

    long l=Double.doubleToLongBits(f);

    hashCode=(int)(l^(l>>>32));

    基本应用类型 hashCode=f.hashCode();

    2、用第一步计算出来的多个hashCode值组合计算出一个hashCode值返回,如:

    1 return f1.hashCode()+(int)f2;

    为了避免直接相加产生偶然相等,可以通过为个Field乘以任意一个质数后相加,如:

    1 return f1.hashCode()*17+(int)f2*13;
  • 相关阅读:
    Python 模块管理
    Python 练习: 计算器
    Linux 系统性能分析工具 sar
    Python 正则介绍
    Python ConfigParser 模块
    Python logging 模块
    Python hashlib 模块
    Python sys 模块
    09 下拉框 数据验证
    08 条件排序
  • 原文地址:https://www.cnblogs.com/wahsonleung/p/3352026.html
Copyright © 2011-2022 走看看