0

Say that we have a class MyClass that does not override equals/hashcode but we want to use it in a java.util.Set. Is it possible to define an equals criteria at the Set declaration? The goal is to accept only one object from MyClass which respect the defined criteria. I know that we can check if the object does not exist before adding it but it's a bit tedious and we lose the interest of using a Set

akuma8
  • 4,160
  • 5
  • 46
  • 82
  • You can't. But you could have a class `MyClassWrapper` that wraps your class and provides proper implementations for `equals` and `hashCode`. Then use that in your set. – Seelenvirtuose Oct 06 '21 at 13:08
  • Thanks, unfortunately I can't create a wrapper. Java designers did not yet finished the job ^^ – akuma8 Oct 06 '21 at 13:23

0 Answers0