基本数据类型
基本数据类型重写的hashCode()方法 相同类容计算出的哈希值一致
String a="abcd";
String b="abcd";
int i = a.hashCode();
int y = b.hashCode();
System.out.println("i="+i+" y="+y); //i=2987074 y=2987074
System.out.println(a.equals(b));//true
String c="重地";
String d="通话";
i=c.hashCode();
y=d.hashCode();
System.out.println("i="+i+" y="+y); //i=1179395 y=1179395
System.out.println(c.equals(d));//false
自定义类,重写hashCode与equals
public class Students {
private String name;
private String ages;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Students students = (Students) o;
return Objects.equals(name, students.name) &&
Objects.equals(ages, students.ages);
}
@Override
public int hashCode() {
return Objects.hash(name, ages);
}
@Override
public String toString() {
return "Students{" +
"name='" + name + '\'' +
", ages='" + ages + '\'' +
'}';
}
public Students(String name, String ages) {
this.name = name;
this.ages = ages;
}
public Students() {
}
}
HashSet<Students> hashSet=new HashSet<>();
hashSet.add(new Students("zhangsan","20"));
hashSet.add(new Students("lisi","30"));
hashSet.add(new Students("zhangsan","30"));
hashSet.add(new Students("zhangsan","20"));
System.out.println(hashSet);//[Students{name='zhangsan', ages='20'}, Students{name='zhangsan', ages='30'}, Students{name='lisi', ages='30'}]`