I have a class with its own hashCode() method. I am adding this class to a HashSet. How can I remove an item by its hashCode, without knowing the object itself?
For example, if I have the following code
HashSet<Data> set = new HashSet<>();
set.add(new Data(10, 5));
...
class Data {
public int importantVal;
public int notImportantVal;
//... constructor ...
@Override
public int hashCode() {
return importantVal;
}
}
and I knew the importantVal
of a Data object, but not the object itself. How would I remove it? set.remove(10)
does not work.
Best solution I can think of is to also override equals()
to return if importantVal
is the same, and then do set.remove(new Data(10, anyPlaceholderValue))
I am looking for a O(1) solution. I obviously know how to loop through the HashSet and check each element, but that is too slow.