ArrayList as key in HashMap

前端 未结 9 1843
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:00

    Unlike Array, List can be used as the key of a HashMap, but it is not a good idea, since we should always try to use an immutable object as the key.

    .toString() method getting the String represtenation is a good key choice in many cases, since String is an immuteable object and can prefectly stands for the array or list.

    0 讨论(0)
  • 2020-11-29 10:02

    ArrayList.equals() is inherited from java.lang.Object - therefore equals() on ArrayList is independent of the content of the list.

    If you want to use an ArrayList as a map key, you will need to override equals() and hashcode() in order to make two arraylists with the same content in the same order return true on a call to equals() and return the same hashcode on a call to hashcode().

    Is there any particular reason you have to use an ArrayList as opposed to say a simple String as the key?

    edit: Ignore me, as Joachim Sauer pointed out below, I am so wrong it's not even funny.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题