[英]What types can we assign to K in HashMap<K,V>?
What types can we assign to K
in HashMap<K,V>
? 我们可以在
HashMap<K,V>
为K
分配什么类型? Is it only numeric types ( int
, float
) or we can assign user defined objects? 是仅数字类型(
int
, float
)还是我们可以分配用户定义的对象?
You can use any type as long as it has sane equals()
and hashCode()
implementations. 您可以使用任何类型,只要它具有合理的
equals()
和hashCode()
实现即可。
Strictly speaking: you can use any reference type, but it won't work as expected if the type doesn't have sane implementations of those methods. 严格来说:您可以使用任何引用类型,但是如果该引用类型没有这些方法的合理实现,它将无法按预期工作。
Note that you can not use the primitive types ( int
, float
, ...) but can use their wrapper types instead ( Integer
, Float
, ...). 请注意,您不能使用基本类型(
int
, float
等),而可以使用其包装器类型( Integer
, Float
等)。 This is because generics can only handle reference types. 这是因为泛型只能处理引用类型。
You can user defined objects, but it is a good idea to define the hashCode
and equals
methods explictly in those classes. 您可以使用用户定义的对象,但是最好在这些类中明确定义
hashCode
和equals
方法。
You cannot use int
or float
because they are primitive types that are not derived from the Object
superclass (which provides a default implementation of hashCode()
and equals()
). 您不能使用
int
或float
因为它们是不是从Object
超类派生的原始类型(它提供了hashCode()
和equals()
的默认实现)。 If you do need to use ints or floats you need to use their object wrapper classes Integer
and Float
如果确实需要使用整数或浮点数,则需要使用它们的对象包装器类
Integer
和Float
您可以将任何类分配给K
,包括其对象形式的基本类型( Integer
, Character
...)。
The only types you cannot use are primitives (and void
), you can instead use wrapper class. 不能使用的唯一类型是基元(和
void
),而可以使用包装器类。 ie the key and values have to be an object (or null). 即键和值必须是一个对象(或null)。
If you want to use primitives, I suggest considering trove4j which is designed to handle primitives in collections efficiently. 如果要使用基元,建议使用trove4j,它旨在有效地处理集合中的基元。
Any object can be used as Key. 任何对象都可以用作Key。
if you use user defined class object as key, be very care on override method hashCode, equals. 如果您将用户定义的类对象用作键,请特别注意覆盖方法hashCode,等于。
take care to use mutable object as key. 注意使用可变对象作为键。 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.
如果在对象是映射中的键的情况下,以影响等值比较的方式更改对象的值,则不会指定映射的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.