我的HashSet包含多个具有相同HashCode的'AccessRequests‘。我只希望有一个实例。我不认为具有相同HashCode的项目可以在HashSet中显示。我在这里做错了什么?
更新:基于假设HashSet只保留列表中不等于另一项的项,并且可能我的equals/hash方法需要简化,我已经更新了我的问题。在我的HashSet中,我仍然会得到多个评估为等于的项目。
下面是来自'AccessRequest‘的HashCode和Equals方法
更新:我更新了我的hash和equals,只包含我需要“相等”的必要字段。
@Override
public int hashCode() {
int hash = 5;
hash = 79 * hash + Objects.hashCode(this.targets);
hash = 79 * hash + Objects.hashCode(this.sources);
hash = 79 * hash + Objects.hashCode(this.destinations);
hash = 79 * hash + Objects.hashCode(this.services);
hash = 79 * hash + Objects.hashCode(this.action);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AccessRequest other = (AccessRequest) obj;
if (!Objects.equals(this.action, other.action)) {
return false;
}
if (!Objects.equals(this.targets, other.targets)) {
return false;
}
if (!Objects.equals(this.sources, other.sources)) {
return false;
}
if (!Objects.equals(this.destinations, other.destinations)) {
return false;
}
if (!Objects.equals(this.services, other.services)) {
return false;
}
return true;
}
在创建AccessRequests之后,我将它们转储到一个HashSet中并迭代:我的HashSet定义如下:
Set<AccessRequest> ars = new HashSet();
ArrayList<AccessRequest> arsAsList = new ArrayList(ars);
for(int position=0;position<arsAsList.size();position++){
AccessRequest fixedAR = arsAsList.get(position);
ArrayList<AccessRequest> comparToList = new ArrayList(ars);
for(int cPosition=0;cPosition<comparToList.size();cPosition++){
AccessRequest nextAR = comparToList.get(cPosition);
if(fixedAR.equals(nextAR)){
System.out.println("position= "+position+" cPosition "+cPosition);
}
}
System.out.println("\n Next AR");
}
以下是输出:
position= 0 cPosition 0
position= 0 cPosition 5
position= 0 cPosition 6
position= 0 cPosition 14
position= 0 cPosition 24
position= 0 cPosition 32
position= 0 cPosition 39
position= 0 cPosition 40
position= 0 cPosition 43
position= 0 cPosition 77
position= 0 cPosition 96
position= 0 cPosition 97
position= 0 cPosition 99
position= 0 cPosition 109
position= 0 cPosition 111
position= 0 cPosition 115
position= 0 cPosition 173
position= 0 cPosition 182
position= 0 cPosition 187
https://stackoverflow.com/questions/56432164
复制相似问题