集合的打印结果:
集合一:
[
{
"cjsj": 1632972963000,
"dm": "a2i1d",
"id": "becb31ad-c6d9-42d4-bde9-60363f57e89b",
"mc": "测试2222",
"sfdm": "1101111",
"zt": 0
},
{
"cjsj": 1621220076000,
"dm": "30010",
"id": "4e4c4a14-2678-4915-b2dd-9acf767ffaf4",
"mc": "名称2",
"zt": 0
}
]
集合二:
[
{
"cjsj": 1632972963000,
"dm": "a2i1d",
"id": "becb31ad-c6d9-42d4-bde9-60363f57e89b",
"mc": "测试2222",
"sfdm": "1101111",
"zt": 0
}
]
取交集结果为:
交集为:[]
对象数值是否相同:false
问题原因:两个集合中的对象是否相等,比对的是对象的地址值
解决:对象里面重写equals方法和 hashCode方法
解决详细:点击
在对象中重写方法:
@Override
public boolean equals(Object obj) {
if (this == obj) return true;//地址相等
//非空性:对于任意非空引用x,x.equals(null)应该返回false。
if (obj == null) return false;
if (obj instanceof MpSxpz) {
MpSxpz other = (MpSxpz) obj;
//需要比较的字段相等,则这两个对象相等
if (equalsStr(this.id, other.id)
&& equalsStr(this.dm, other.dm)
&& equalsStr(this.fid, other.fid)
&& equalsStr(this.sfdm, other.sfdm)) {
return true;
}
}
return false;
}
private boolean equalsStr(String str1, String str2) {
if (StringUtils.isEmpty(str1) && StringUtils.isEmpty(str2)) {
return true;
}
if (!StringUtils.isEmpty(str1) && str1.equals(str2)) {
return true;
}
return false;
}
@Override
public int hashCode() {
int result = 17;
result = 31 * result + (id == null ? 0 : id.hashCode());
result = 31 * result + (dm == null ? 0 : dm.hashCode());
result = 31 * result + (fid == null ? 0 : fid.hashCode());
result = 31 * result + (sfdm == null ? 0 : sfdm.hashCode());
return result;
}
重写之后输出结果:
交集为:[{"cjsj":1632972963000,"dm":"a2i1d","id":"becb31ad-c6d9-42d4-bde9-60363f57e89b","mc":"测试2222","sfdm":"1101111","zt":0}]
对象是否数值相同:true
.
.
.
就此完成!!!