gpt4 book ai didi

java - StringBuffer 可以用作 HashMap 中的键吗?

转载 作者:行者123 更新时间:2023-11-29 03:05:06 26 4
gpt4 key购买 nike

StringBuffer 可以作为 HashMap 中的键吗?
如果是这样,使用 String 和 StringBuffer 作为键有什么区别?

最佳答案

Can a StringBuffer as a key in a HashMap?

不,因为 StringBuffer既不覆盖 equals 也不覆盖 hashCode,因此它不适合作为 HashMap 键(回想一下 HashMap 依赖于那些判断给定键是否存在于映射中的两种方法)。

除此之外,StringBuffer 是可变的,您通常希望 Map 键是不可变的。来自 Map :

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.

关于java - StringBuffer 可以用作 HashMap 中的键吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32561553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com