Reputation: 2402
I have a Set<SelectDTO>
with a single element and I'm failing when using .contains with it and a new SelectDTO, as follows:
Set<SelectDTO> setDTOs = new HashSet<SelectDTO>
//processing where an element with <name = "ME101", id = 102> is added.
SelectDTO selectDTO = new SelectDTO();
selectDTO.setName("ME101");
selectDTO.setId(102);
if (!setDTOs.contains(selectDTO)){
throw new Exception();
}
I have override SelectDTO's .hashCode()
, so that it's calculated as the sum of the parameters id and name. I have debugged and confirmed that the execution goes through .hashCode()
two times: the first when the element is added to the set and the second when calling .contains()
. Both elements' hashCode is -2024486876. But also, when debugging, I see that the table within the set has a single element, its "hash" being -1909995738.
This is the code for my hashCode, although I don't think the problem's there:
@Override
public int hashCode() {
int result = 0;
result += this.getName() != null ? this.getName().hashCode() : 0;
result += this.getId() != null ? this.getId() : 0;
return result;
}
I guess that .contains()
is using this 'hash' value to compare, but I don't know why.
Upvotes: 0
Views: 1902
Reputation: 68715
It seems you forgot to add the selectDTO element in Set:
setDTOs.add(selectDTO);
Assuming you have added the element somewhere in your code, then you need to override the equals method and not hashCode. As contains() method uses equals() method to determine whether an element exist or not in the set. Interestingly, i believe this is how Set makes sure it does not push a duplicate element in the Set.
Upvotes: 0
Reputation: 9705
From the Set.contains() documentation:
Returns
true
if this set contains the specified element. More formally, returnstrue
if and only if this set contains an elemente
such that(o==null ? e==null : o.equals(e))
.
In other words, you do not only need to implement hashCode()
, but also equals()
.
Upvotes: 4