Caching hashes in Java collections?

前端 未结 5 415
一向
一向 2021-01-23 17:26

When I implement a collection that uses hashes for optimizing access, should I cache the hash values or assume an efficient implementation of hashCode()?

On

5条回答
  •  死守一世寂寞
    2021-01-23 17:49

    On the other hand, when I implement a class that overrides hashcode(), should I assume that the collection (i.e. HashSet) caches the hash?

    No, you should not make any assumptions beyond the scope of the class you are writing.

    Of course you should try to make your hashCode cheap. If it isn't, and your class is immutable, create the hashCode on initialization or lazily upon the first request (see java.lang.String). If your class is not immutable, I don't see any other option than to re-calculate the hashCode every time.

提交回复
热议问题