My HashSet contains multiple 'AccessRequests' with the same HashCode. I only want there to be one instance. I didn't think items with the same HashCode could show up in a HashSet. What am I doing wrong here?
UPDATE: Based on the assumption that HashSet keeps only an item that is not equal to another in a list AND that perhaps my equals/hash methods needed simplification, I have updated my problem. I am still getting MULTIPLE items that evaluate to Equals in my HashSet.
Below are the HashCode and Equals methods from 'AccessRequest'
UPDATE: I updated my hash and equals to only have the necessary fields I need to be "equal"
@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;
}
After Creating the AccessRequests, I dump them into a HashSet and Iterate: My HashSet is defined as below:
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");
}
The following is the output:
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