Overriding GetHashCode for mutable objects?

前端 未结 5 1422
野性不改
野性不改 2020-11-29 21:51

I\'ve read about 10 different questions on when and how to override GetHashCode but there\'s still something I don\'t quite get. Most implementations of

5条回答
  •  生来不讨喜
    2020-11-29 22:44

    I don't know about C#, being a relative noob to it, but in Java, if you override equals() you need to also override hashCode() to maintain the contract between them (and vice-versa)... And java also has the same catch 22; basically forcing you use immutable fields... But this is an issue only for classes which are used as a hash-key, and Java has alternate implementations for all hash-based collections... which maybe not as fast, but they do effecitely allow you to use a mutable object as a key... it's just (usually) frowned up as a "poor design".

    And I feel the urge to point out that this fundamental problem is timeless... It's been around since Adam was a lad.

    I've worked on fortran code which is older than I am (I'm 36) which breaks when a username is changed (like when a girl gets married, or divorced ;-) ... Thus is engineering, The adopted solution was: The GetHashCode "method" remembers the previously calculated hashCode, recalculates the hashCode (i.e. a virtual isDirty marker) and if the keyfields have changed it returns null. This causes the cache to delete the "dirty" user (by calling another GetPreviousHashCode) and then the cache returns null, causing the user to re-read from the database. An interesting and worthwhile hack; even if I do say so myself ;-)

    I'll trade-off mutability (only desirable in corner cases) for O(1) access (desirable in all cases). Welcome to engineering; the land of the informed compromise.

    Cheers. Keith.

提交回复
热议问题