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

4
  • Simplest is set.removeIf(v -> v.getImportantVal() == importantVal);. Not sure why you're using that as the hash code. Commented May 19, 2021 at 5: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. Commented May 19, 2021 at 5:31
  • Maybe use a HashMap<Integer, List<Data>> instead of a HashSet<Data>. Commented May 19, 2021 at 5: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 Commented May 19, 2021 at 5:35

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.