zoukankan      html  css  js  c++  java
  • 重写Object.hashCode()方法总结

    定义

    散列码(hash code)是根据对象内容导出的一个整型值,用于标识不同的对象;

    而Object类中有默认的hashcode()方法,其值是对象的存储地址

    自定义对象重写hashcode()

    思路:分别调用类的实例域的hashcode()然后相加来得到该类的hashcode

    调用null安全的Objects.hash(Object...objects)来得到总的hashcode

    举例:Manager(String sex,int bonus)

        @Override
        public int hashCode() {
            return Objects.hash(sex,bonus);
        }

     若是继承了父类Person,则应该加上super.hashcode()

        @Override
        public int hashCode() {
            return Objects.hash(sex,bonus)+super.hashCode();
        }

    与equals关联

    equals与hashcode的定义必须一致,即equals返回值要跟hashcode返回值一致

    举例:x.equals(y)=true -> x.hashcode()=y.hashcode

    因此,一旦重写了类的equals方法就应该重写其hashcode()方法

    举例:若Manager.equals是当sex相等时返回true

        @Override
        public boolean equals(Object obj) {
            //1.如果引用相同的对象直接返回true
            if(this==obj)return true;
            //2.因为能够调用equals则表明this不为null,所以如果obj为null,直接返回false
            if(obj==null)return false;
            //3.精确要求类型相等
            if(getClass()!=obj.getClass())return false;
            //4.将obj强制类型转换为当前类型
            Manager object=(Manager)obj;
            //5.域一一对比,因为对象如String要使用equals则必须确保它的域参数不为null,所以要采用Objects.equals(field1,field2)来对比
            return  Objects.equals(this.sex,object.sex);
        }

    此时hashcode就只需要计算sex的hash值

        @Override
        public int hashCode() {
            return Objects.hash(sex);
        }

    数组的hashcode

    Arrays.hashcode(type[] array);

  • 相关阅读:
    angularJS指令--在各自的控制器里调用不同的函数
    npm install时的一个小问题
    按特定形式生成当前日期的函数
    js判断对象是否是数组的方法
    转正考试的几个考点
    JS 对象转化为数组
    requireJS随笔
    使用bootstrap-select插件,赋初始值
    理解Stream(一)——串行与终止操作
    python requests 库 首次使用
  • 原文地址:https://www.cnblogs.com/ming-szu/p/9158394.html
Copyright © 2011-2022 走看看