package mianshi;
import java.util.HashSet;
import java.util.Set;
public class Equals_HashcodeDemo2 {
public static void main(String[] args) {
Set<Student> s = new HashSet<Student>();
//使用hashcode和equals。在进行对象保存的时候,先根据hashcode产生的哈希码,找到相应的哈希桶
//所以哈希码不一样的对象,equals一定返回false。
//在相同的哈希桶中在用equals进行比较,这样就可以缩短比较的对象所花的时间,效率高。
//equals返回true,那么hashcode一定相等
//equals返回false,对hashcode没有影响
//hashcode不相同,那么equals一定返回false
//hashcode相同,对equals的结果没有影响
//名字是--ta,哈希码---580
Student s1 = new Student("tom");
//名字是--dfd,哈希码---500
Student s2 = new Student("dfd");
//名字是--tom,哈希码---580,
Student s3 = new Student("ta");
s.add(s1);
s.add(s2);
s.add(s3);
System.out.println(s);
}
}
class Student{
private String name;
public Student(String name){
this.name = name;
}
public int hashCode() {
// 通过name来产生hashcode,所以产生的哈希桶都是分别以首字母为标准,来群分和其他的桶的不同
// 当我们通过hashcode来进行保存时候,首先根据hashcode来查找相应的哈希桶,
// 然后就只要和在这个桶里面的对象进行比较,而不用和所有的对象进行比较,提高了效率
//hashcode的产生方法涉及到算法,这一般不是我们考虑的问题,而是由专门的算法专家进行规定和设计
return this.name.charAt(0)*5;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if(!(obj instanceof Student)){
return false;
}else{
Student student = (Student)obj;
return student.name == this.name;
}
}
public String toString(){
return "名字是--"+this.name+",哈希码---"+this.hashCode();
}
}
本文探讨了在Java中如何正确实现equals()方法与hashCode()方法,并通过具体示例展示了这些方法在HashSet中的作用原理。文章解释了为什么正确的实现对于集合类的有效工作至关重要。
1028

被折叠的 条评论
为什么被折叠?



