hashCode和equals作用

hashCode()是Java中用于定位对象在哈希表中位置的关键方法,尤其在HashMap和HashSet中起到重要作用。当插入元素时,hashCode()决定插入位置,而equals()用于检查键值对是否相同。如果未正确重写hashCode(),可能导致相等对象在集合中无法正确识别。例如,HashSet在存储相等对象时,依赖于hashCode()的一致性,以确保添加重复元素时能正确处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

什么是hashCode()

  • hashCode()的作用是获取哈希码,返回一个int整数,作用是查找hashMap的索引位置。hashCode()在JDK的Object类中,也就表明每一个类中都有此方法。hashCode()是C++编写的本地方法。
  • public native int hashcode();

为什么有hashCode()

  • 用HashMap来举例hashCode()的作用,当往HashMap里插入一个元素之后,通过hashCode()确定插入的位置,如果该位置如果为空直接插入,如果有则equals()方法比较与该位置的下所用键值是否相同,如果相同就将value进行替换,否则插入在链表末尾(jdk1.8)。hadeCode()可以减少equals的比较次数,缩小查找的成本。

为什么重写equals()时要重写hashCode()

  • 两个对象相等hashCode()必须相同,两个对象相等,两个对象调用的equals()方法返回为true。两个相等的hashCode(),并不一定是相同的对象。
  • hashCode() 的默认⾏为是对堆上的对象产⽣独特值。如果没有重写 hashCode() ,则该class 的两个对象⽆论如何都不会相等(即使这两个对象指向相同的数据)
  • HashSet举例
public class Test{
	Student stu1 = new Student(111);
	Student stu2 = new Student(111);
	HashSet<Student> set = new HashSet();
	System.out.print(set.add(stu1)) //true;
	System.out.print(set.add(stu1)) //true;
}

public Student{
	private int studentId;
	public Student(int studentId){
		this.studentId = studentId;
	}
	@Override
50   public boolean equals(Object obj){  
51        if(obj == null){  
52          return false;  
53         }  
54      
55         //如果是同一个对象返回true,反之返回false  
56         if(this == obj){  
57           return true;  
58         }  
59               
60             //判断是否类型相同  
61         if(this.getClass() != obj.getClass()){  
62                 return false;  
63         }  
64         
65         Student stu= (Student)obj;  
66         return  studentId  ==  stu.studentId  e;  
67   } 
}
```java
public class Test{
	Student stu1 = new Student(111);
	Student stu2 = new Student(111);
	HashSet<Student> set = new HashSet();
	System.out.print(set.add(stu1)) //true;
	System.out.print(set.add(stu1)) //false;
}

public Student{
	private int studentId;
	public Student(int studentId){
		this.studentId = studentId;
	}
	 @Override
53   public int hashCode(){  
55        return studentId % 16;
56   }
	@Override
50   public boolean equals(Object obj){  
51        if(obj == null){  
52          return false;  
53         }  
54      
55         //如果是同一个对象返回true,反之返回false  
56         if(this == obj){  
57           return true;  
58         }  
59               
60             //判断是否类型相同  
61         if(this.getClass() != obj.getClass()){  
62                 return false;  
63         }  
64         
65         Student stu= (Student)obj;  
66         return  studentId  ==  stu.studentId  e;  
67   } 
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值