2

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 ?

raman r
  • 41
  • 5

3 Answers3

7

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?

Chathura Buddhika
  • 2,067
  • 1
  • 21
  • 35
4

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

Thilo
  • 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
    "Helpful" is another alternative I like :) – Andy Turner Aug 24 '17 at 08:14
-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");