Understanding Common Features in Object Initialization

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

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

I understand that the first initialization is the definition of generics in constructing an object, but I do not understand the fundamental consequences of this, and not the construction of the last object (maplet2). In practice, I have always seen that the code uses the maplet1 construct, but I don’t understand where it would be beneficial to do this on another.

+4
source share
3 answers

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

For more details, see What is a Raw Type and Why Shouldn't We Use It?

+5
source

The first is type safe.

You can shorten the right side using the diamond operator <> . This operator enters the type parameters on the left side of the job.

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

+2
source

Lets you understand the concept of Erasure. With RUNTIME, the HashMap<String, String>() and HashMap() are the same as the HashMap.

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

Without using Generics, you should throw, say, a value in Map, in String Explicitly every time.

Using generics makes you eliminate the roll.

If you are not using Generics, there is a high chance that a future developer may insert another type of object that will ClassCastException

+1
source

All Articles