Mahendran
Mahendran

Reputation: 2719

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

What types can we assign to K in HashMap<K,V>? Is it only numeric types (int, float) or we can assign user defined objects?

Upvotes: 0

Views: 492

Answers (5)

swanliu
swanliu

Reputation: 791

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.

Upvotes: 0

Dunaril
Dunaril

Reputation: 2795

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

Upvotes: 2

Peter Lawrey
Peter Lawrey

Reputation: 533660

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.

Upvotes: 1

Matthew
Matthew

Reputation: 13332

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

Upvotes: 6

Joachim Sauer
Joachim Sauer

Reputation: 308131

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.

Upvotes: 10

Related Questions