开发者

What types can we assign to K in HashMap<K,V>?

What ty开发者_运维技巧pes can we assign to K in HashMap<K,V>? Is it only numeric types (int, float) or we can assign user defined objects?


You can use any type as long as it has sane equals() and hashCode() implementations.

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, ...). 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.

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()). If you do need to use ints or floats you need to use their object wrapper classes Integer and Float


You can assign any class to K, including primitive types in their object forms (Integer, Character...).


The only types you cannot use are primitives (and void), you can instead use wrapper class. i.e. the key and values have to be an object (or null).

If you want to use primitives, I suggest considering trove4j which is designed to handle primitives in collections efficiently.


Any object can be used as Key.

  1. if you use user defined class object as key, be very care on override method hashCode, equals.

  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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜