简体   繁体   English

我们可以在HashMap中将哪些类型分配给K <K,V> ?

[英]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? 是仅数字类型( intfloat )还是我们可以分配用户定义的对象?

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 , ...). 请注意,您不能使用基本类型( intfloat等),而可以使用其包装器类型( IntegerFloat等)。 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. 您可以使用用户定义的对象,但是最好在这些类中明确定义hashCodeequals方法。

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() ). 您不能使用intfloat因为它们是不是从Object超类派生的原始类型(它提供了hashCode()equals()的默认实现)。 If you do need to use ints or floats you need to use their object wrapper classes Integer and Float 如果确实需要使用整数或浮点数,则需要使用它们的对象包装器类IntegerFloat

您可以将任何类分配给K ,包括其对象形式的基本类型( IntegerCharacter ...)。

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。

  1. if you use user defined class object as key, be very care on override method hashCode, equals. 如果您将用户定义的类对象用作键,请特别注意覆盖方法hashCode,等于。

  2. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM