4

I have a basic question about generics in Java: what is difference between the following two initializations of a map?

        Map<String, String> maplet1 = new HashMap<String, String>();

        Map<String, String> maplet2 = new HashMap();

I understand the the first initialization is specifying the generics in the object construction, but I don't understand the underlying ramifications of doing this, rather than the latter object construction (maplet2). In practice, I've always seen code use the maplet1 construction, but I don't understand where it would be beneficial to do that over the other.

matts
  • 6,738
  • 1
  • 33
  • 50
Sal
  • 3,179
  • 7
  • 31
  • 41
  • What makes you think there is a difference? –  Feb 27 '13 at 23:41
  • 3
    There is no functional difference. the benefit is it does not cause a compiler warning so you don't have to sort "real" raw type warnings from "sloppy syntax" raw type warnings. – Affe Feb 27 '13 at 23:48
  • 1
    But note that @Affe's comment is only true for a no-arg constructor. Consider that this compiles: `Map maplet2 = new HashMap(mapOfIntsToLongs);` – Paul Bellora Feb 28 '13 at 02:58

3 Answers3

5

The second Map is assigned to a raw type and will cause a compiler warning. You can simply use the first version to eliminate the warning.

For more see: What is a raw type and why shouldn't we use it?

Community
  • 1
  • 1
Reimeus
  • 158,255
  • 15
  • 216
  • 276
2

The first one is type-safe.

You can shorthand the right side by using the diamond operator <>. This operator infers the type parameters from the left side of the assignment.

Map<String, String> maplet2 = new HashMap<>();

Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
1

Lets understand the concept of Erasure. At RUNTIME HashMap<String, String>() and HashMap() are the same represented by HashMap.

The process of converting HashMap<String,String> to HashMap (Raw Type) is called Erasure.

Without the use of Generics , you have to cast , say the value in the Map , to String Explicitly every time.

The use of Generics forces you to Eliminate cast.

If you don't use Generics , there will be high probability that a Future Developer might insert another type of Object which will cause ClassCastException

user1428716
  • 2,078
  • 2
  • 18
  • 37