如果两个对象的hashCode和equals都相等,那么才能认为两个对象是相等的。
先来看一段代码:(Set集合会自动过滤重复的对象)
public class Buys {
private int total;
public Buys(){}
public Buys(int total){
this.total = total;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
}
public static void main(String[] args){
Set<Buys> set = new HashSet<>();
set.add(new Buys(0));
set.add(new Buys(0));
set.add(new Buys(1));
System.out.println("setk集合的长度:"+set.size());
Iterator<Buys> it = set.iterator();
while (it.hasNext()) {
Buys buys = it.next();
System.out.println("hashcode:"+buys.hashCode());
System.out.println("总共:"+buys.getTotal());
}
}
运行结果如下:
set集合的长度:3
hashcode:1956725890
总共:1
hashcode:1163157884
总共:0
hashcode:460141958
总共:0
从运行结果上来看,set集合的长度是3,说明赋值的三个对象都不是一个对象,打印出的hashcide值也能说明是三个不同的对象。
OK,我们来改造一下Buys对象:
重写hashCode和equals方法
public class Buys {
private int total;
public Buys(){}
public Buys(int total){
this.total = total;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
@Override
public boolean equals(Object obj) {
return this.total == ((Buys)obj).total;
}
@Override
public int hashCode() {
return total;
}
}
运行结果如下:
set集合的长度:2
hashcode:0
总共:0
hashcode:1
总共:1
从运行结果上来看,set集合的长度是2,说明当两个对象hashCode一样并且equals返回值为true时,我们就认为两个对象是同一个对象。