0

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))

Will Kanga
  • 652
  • 1
  • 6
  • 12
  • Simplest is `set.removeIf(v -> v.getImportantVal() == importantVal);`. Not sure why you're using that as the hash code. – ernest_k May 19 '21 at 05:16
  • Simplest, yes, but that won't be at all performant, because it will check the `importantVal` of every object in the set, rather than taking advantage of the fact that that's the hash code. – Dawood ibn Kareem May 19 '21 at 05:31
  • Maybe use a `HashMap>` instead of a `HashSet`. – Dawood ibn Kareem May 19 '21 at 05:33
  • whoever closed the question, the links you provided are completely useless. I think its assumed that I'm looking for a performant solution. I obviously know how to write a for each loop – Will Kanga May 19 '21 at 05:35

0 Answers0