在List集合中放置一个实体类对象如何使用contains类进行比较是否为对象的子集
listDrugAsocDOS.contains(listDrugAsocDO)
在contains源码中发现
public boolean contains(Object o) {
Iterator<E> it = iterator();
if (o==null) {
while (it.hasNext())
if (it.next()==null)
return true;
} else {
while (it.hasNext())
if (o.equals(it.next()))
return true;
}
return false;
}
contains方法是底层是使用equals方法进行比较所以,实体类中只要有部分不同就集合不是子集。所以我们想使用部分实体类的部分元素进行比较是否为子集就需要我们去重写实体类的equals的方法。
比如:在mybatis中使用雪花算法进行id的插入,在插入两条相同的数据但是他们的id是不能相同的所以使用这个contains方法就是行不通的
重写equals的技巧(当然也带重写hashCode),将需要比较的字段拼接在string的字符串中进行比较
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ListDrugAsocDO that = (ListDrugAsocDO) o;
String thisStr = tenditmId + "-" + druglistId + "-" + drugCode;
String thatStr = that.tenditmId + "-" + that.druglistId + "-" + that.drugCode;
return thisStr.equals(thatStr);
}
@Override
public int hashCode() {
return Objects.hash(tenditmId, druglistId, drugCode);
}