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 ?
-
7Because `double[]` is a reference type (it's a subclass of `Object`), not a primitive. – Andy Turner Aug 24 '17 at 06:52
-
1`double` is primitive, `double[]` is not. – Maroun Aug 24 '17 at 06:54
-
See also [Is an array a primitive type or an object](https://stackoverflow.com/a/12807748/8051589). – Andre Kampling Aug 24 '17 at 07:00
3 Answers
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?

- 2,067
- 1
- 21
- 35
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).

- 257,207
- 101
- 511
- 656
-
"proper" implementations of equals or hashCode: Or `toString` for that matter. `java.util.Array` provide all these as static helper methods, but the array itself does not dispatch there. – Thilo Aug 24 '17 at 07:04
-
I would say "useful" or "intuitive" rather than "proper": they are proper in the sense that they exist and can be invoked like any other. – Andy Turner Aug 24 '17 at 07:29
-
I put "proper" in quotes as a compromise. But the default implementations are really not very helpful and cause a lot of questions here on this site, so I have to insist that they are somewhat broken (and would probably do what these helper methods do if the language was re-designed). – Thilo Aug 24 '17 at 07:35
-
1
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");

- 719
- 6
- 14