ArrayList as key in HashMap

前端 未结 9 1841
Happy的楠姐
Happy的楠姐 2020-11-29 09:17

Would it be possible to add an ArrayList as the key of HashMap. I would like to keep the frequency count of bigrams. The bigram is the key and the

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 10:07

    From the documentation:

    Note: great care must be exercised if mutable objects are used as map keys. The behavior of a map is not specified if the value of an object is changed in a manner that affects equals comparisons while the object is a key in the map. A special case of this prohibition is that it is not permissible for a map to contain itself as a key. While it is permissible for a map to contain itself as a value, extreme caution is advised: the equals and hashCode methods are no longer well defined on such a map.

    You have to take care when you are using mutable objects as keys for the sake of hashCode and equals.

    The bottom line is that it is better to use immutable objects as keys.

提交回复
热议问题