数据结构 玩转数据结构 14-3 java中的hashCode方法

发布时间 2023-12-03 11:34:50作者: 菜鸟乙

0    课程地址

https://coding.imooc.com/lesson/207.html#mid=15346

 

1    重点关注

1.1    重写hashCode和equals方法

参见3.1

 


 

2    课程内容

2.1    不同的对象的默认hashCode方法

Integer  相同数字的一样

Double  相同数字的一样

String    相同字符串的一样

对象      比较的是引用的地址, new两次相同的对象,地址不同,所以哈希值不同

对象      重写,重写对象的hash方法后,哈希值相同

详见3.1

 

 

 

 

 

 

 

3    Coding

3.1    重写hashCode和equals方法

  • 测试类:
package com.example.jiayou.ceshi;

public class Test2 {

    public static void main(String[] args) {

        /**
         * 1整数哈希值   值固定
         */
        int a = 6;
        System.out.println(((Integer)a).hashCode());

        int b = -6;
        System.out.println(Integer.hashCode(b));

        /**
         * 2小数哈希值   值固定
         */
        System.out.println(Double.hashCode(3.2));

        /**
         * 3字符串哈希值  值固定
         */
        System.out.println("ccc".hashCode());


        Man man = new Man("110",15);
        Man man2 = new Man("110",15);
        /**
         * 4对象哈希值重写 值固定
         */
        System.out.println(man.hashCode());
        System.out.println(man2.hashCode());

        /**
         * 5对象哈希值不重写 值不固定
         */
        System.out.println(man.hashCode());
        System.out.println(man2.hashCode());

    }

}

 

  • 主类:
package com.example.jiayou.ceshi;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class Man {

    private String idNo;
    private int age;

    //比较hashCode,无视大小写
    public int hashCode(){
        int B = 31;//随便定义,类比前一节小写字母
        int hash = 0;
        hash = hash*B+idNo.toLowerCase().hashCode();
        hash = hash*B+age;
        return hash;
    }

    public boolean equals(Object obj){
        //1 对象地址引用一样,一定是同一对象
        if(this==obj){
            return true;
        }

        //2 不同:通用为null
        if(null==obj){
            return false;
        }

        //3 不同:通用继承情况
        if(this.getClass()!=obj.getClass()){
            return false;
        }

        Man man = (Man)obj;
        //4 相同:属性完全一致
        if(man.getAge()==this.getAge()&&
                man.getIdNo().hashCode()==this.getIdNo().hashCode()){
            return true;
        }
        return false;

    }

}