Reputation: 41
I'm developing an java application in which I use Hashmap which takes string as key and double as value, but I know Hashmap cannot take primitive type as generics but it can take double[].May I know why ?
Upvotes: 2
Views: 1685
Reputation: 2195
You can't use double
since it is a primitive. But you can use Double
instead.
Refer following question for more detail.
Why can Java Collections not directly store Primitives types?
Upvotes: 7
Reputation: 728
You cannot use primitive types (int, boolean, double, etc.) as map keys or values. But each primitive type has one wrapper class (int - Integer, double - Double, etc.) that you can use instead.
Since Java 1.5 the conversion of primitive values to wrapper objects is automatic (it's called auto boxing/unboxing):
Map<String, Double> m = new HashMap<>();
m.add("a", 1.0 );
double a = m.get("a");
Upvotes: -1
Reputation: 262554
All arrays are objects in Java, including arrays of primitive types.
This means that you can use them as generic type parameters (whereas primitives cannot be used), for example as List
elements or Map
values. They can stand in anywhere you need an Object
.
But note that arrays do not have "proper" implementations of equals
or hashCode
, and thus make terrible keys in a Map
(values are fine).
Upvotes: 4