一个StringBuffer可以用作HashMap中的一个键吗? [英] Can a StringBuffer be used as a key in a HashMap?

查看:238
本文介绍了一个StringBuffer可以用作HashMap中的一个键吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以将StringBuffer作为HashMap中的键吗?

如果是这样,使用String和StringBuffer作为键有什么区别?

解决方案


StringBuffer可以作为HashMap中的键吗?

不,自 StringBuffer 不会覆盖等于 hashCode ,所以它不适合作为 HashMap 键(回想一下 HashMap 依靠这两种方法来判断给定的键是否存在于map中)。 $ b

除此之外, StringBuffer s是可变的,你通常希望 Map 键是不可变的。从 地图


注意:如果可变对象用作映射键,则必须非常小心。如果对象的值以影响等于比较的方式进行更改,而对象是地图中的键,则不会指定地图的行为。这种禁令的一个特例是,地图不允许自己作为关键字。虽然地图允许将自己作为一个值包含在内,但是建议您特别小心:等于 hashCode 方法在这样的地图上不再有明确的定义。



Can a StringBuffer as a key in a HashMap?
If so, what is the difference between using a String and a StringBuffer as the key?

解决方案

Can a StringBuffer as a key in a HashMap?

No, since StringBuffer overrides neither equals nor hashCode, so it is not suitable as a HashMap key (recall that HashMap relies on those two methods to tell if a given key is present in the map).

Beyond that, StringBuffers are mutable, and you typically want Map keys to be immutable. From 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.

这篇关于一个StringBuffer可以用作HashMap中的一个键吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆