5

Is this a good design pattern to enforce a class not being used in any hash-based collection (HashMap, HashSet, etc), or could this have unintended consequences?

class DoNotUseInHashBasedCollection {
    @Override
    public int hashCode() {
        throw new UnsupportedOperationException();
    }
}
F. George
  • 4,970
  • 4
  • 20
  • 38
  • Oh it will most likely have unintended consequences. Is there a reason the class can't be used in hash based collections? – Kayaman Dec 08 '16 at 08:59
  • I was thinking about singletons / controller classes, failing fast instead of having a broken collection. – F. George Dec 08 '16 at 09:03
  • Why would the collection break? – Kayaman Dec 08 '16 at 09:28
  • It wouldn't "break" the collection, but it may result in unintended behaviour. The reason I asked this question is not because I have this problem now, but because I see this as a *potential* solution for future situations. I say potential because I - as asked in the OP - still do not know if core classes other than those in the collections framework access `.hashCode()`. – F. George Dec 08 '16 at 15:16
  • You're creating an imaginary problem. With typed collections there's no way that your objects will get into hash based collections by accident, and even if they did, what's the big deal? You wouldn't make `toString()` throw an exception just because you don't want it to be displayed as a string, would you? – Kayaman Dec 08 '16 at 17:03
  • Can you come up with a realistic scenario where this could cause problems? Cause I can't come up with any. – Kayaman Dec 08 '16 at 17:12
  • `equals` is often overriden for testing purposes. it's well known that we should override `hashcode` everytime we override `equals`. Throwing `UnsupportedOperationException` we say that this class is not designed to be used as a key. So for me question makes sense. – Oleg Vazhnev Feb 11 '19 at 09:57
  • I am just thinking about the same question. What about mutable objects? Throwing an UnsupportedOperationException seems to be an easy way to prohibit that any user puts such an mutable object in a HashSet or uses it as key in a HashMap. – user3199797 Jun 01 '20 at 19:13

0 Answers0