前提:
将一个对象,当做key存入map中。
问题:
使用map.containsKey()方法,判断对象是否已存在于map中时,发现尽管传入的对象属性一致,值也一致,但方法返回的结果一直是找不到。
原因:
虽然两个对象的属性值相同,但是毕竟它们两个是不同的对象,对于map中存取值,都是依据key的hashcode值,通过计算后存到对应的桶里。因为默认的hashcode值计算方式,与对象的地址有一定的联系,所以,不同的对象计算出来的hashcode值一般也不会相同,所以在取值存值的时候会像上边一样。
解决方案:
对对象类重写hashCode、equals方法
示例:
//新建类,作为map的key
static class Temp {
private String period;//会计期间
private String dept;//部门
private String fund;//资金用途
private String currency;//币别
public String getPeriod() {
return period;
}
public void setPeriod(String period) {
this.period = period;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
public String getFund() {
return fund;
}
public void setFund(String fund) {
this.fund = fund;
}
public String getCurrency() {
return currency;
}
public void setCurrency(String currency) {
this.currency = currency;
}
//重写hashcode方法
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((period == null) ? 0 : period.hashCode());
result = prime * result + ((dept == null) ? 0 : dept.hashCode());
result = prime * result + ((fund == null) ? 0 : fund.hashCode());
result = prime * result + ((currency == null) ? 0 : currency.hashCode());
return result;
}
//重写equals方法
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Temp other = (Temp) obj;
if (period == null) {
if (other.period != null)
return false;
} else if (!period.equals(other.period))
return false;
if (dept == null) {
if (other.dept != null)
return false;
} else if (!dept.equals(other.dept))
return false;
if (fund == null) {
if (other.fund != null)
return false;
} else if (!fund.equals(other.fund))
return false;
if (currency == null) {
if (other.currency != null)
return false;
} else if (!currency.equals(other.currency))
return false;
return true;
}
}Map<Temp, DynamicObject> map = new HashMap<>();
Temp temp = new Temp();
temp.setPeriod(dateStr);
temp.setCurrency(currency);
temp.setDept(dept);
temp.setFund(fund);
if (map.containsKey(temp)) {
//累加实付金额
entryItem.set(KEY_PAY_SFJE, map.get(temp).getBigDecimal(KEY_PAY_SFJE).add(entryItem.getBigDecimal(KEY_PAY_SFJE)));
}
map.put(temp, entryItem);版权声明:本文为ChickenBro_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。