Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding Generics in Object Initialization

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.

like image 783
Sal Avatar asked Feb 17 '23 09:02

Sal


2 Answers

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?

like image 152
Reimeus Avatar answered Feb 27 '23 14:02

Reimeus


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<>();

like image 26
Mr. Polywhirl Avatar answered Feb 27 '23 13:02

Mr. Polywhirl