hashCode和equals作用

2023-05-16

什么是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   } 
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

hashCode和equals作用 的相关文章

随机推荐