ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

hashcode 和 equals

2022-01-08 09:32:48  阅读:150  来源: 互联网

标签:xxx equals hashcode Student println new Man


先看个例子

@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student {
    private String name;
    private String addr;

    public int hashCode() {
         return 1;
    }
    public boolean equals(Object obj) {
        return true;
    }
}
@Data
@NoArgsConstructor
@AllArgsConstructor
class Man {
    private String name;
    private String addr;
}

public static void main(String[] args) {
	Student student = new Student("xxx", "xxx");
	Student student2 = new Student("yyy", "yyy");
	System.out.println(student.equals(student2));// true
	Man man = new Man("xxx", "xxx");
	Man man2 = new Man("yyy", "yyy");
	System.out.println(man.equals(man2));// false
	
	// 以下是将Student中覆写equals方法注释,留下hashcode方法
	Student student = new Student("xxx", "xxx");
    Student student2 = new Student("xxx", "xxx");
    System.out.println(student.equals(student2));// false
    
	// 以下是将Student中覆写hashcode方法注释,留下equals方法
	Student student = new Student("xxx", "xxx");
    Student student2 = new Student("xxx", "xxx");
    System.out.println(student.equals(student2));// true
    
    // 以下是没有修改Man中的属性及方法修改的情况下
    Man man = new Man("xxx", "xxx");
	Man man2 = new Man("xxx", "xxx");
	System.out.println(man.equals(man2));// true
    System.out.println("man : "+man.hashCode());//  7153081
    System.out.println("man2: "+man2.hashCode());// 7153081
	
	// 以下是覆写Man中的equals 和hashcode方法,与Student中覆写保持相同的返回值
	Student student = new Student("111", "111");
	Man man = new Man("xxx", "xxx");
	System.out.println(man.equals(student));// true
	// 
}

获取哈希码,也称为散列码,通过返回一个int值确定对象在hash表中的索引位置,其定义在object中,所以任何类都包含hashcode()函数;

例如:HashSet在添加数据的时候会先通过hashcode()计算该位置是否有值,有值再通过equals来检查两个对象是否相同,相同的话加入失败,成功的话重新散列到其他文职,减少了equals的次数,增加了执行速度

  • HashCode值一致不一定是一个对象
  • 相等的对象的HashCode的值一定是一样的
  • 相等的对象调用equals方法返回的都是true;
  • 所以在重写equals方式的时候HashCode的方法也需要被重写;
  • hashcode()的默认行为是在堆上的对象产生独特值,
  • 如果没有重写hashcode,则两个class无论如何都不会相等

标签:xxx,equals,hashcode,Student,println,new,Man
来源: https://blog.csdn.net/qq_43180307/article/details/122360436

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有