Sal
Sal

Reputation: 3269

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.

Upvotes: 4

Views: 198

Answers (3)

Reimeus
Reimeus

Reputation: 159754

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?

Upvotes: 5

user1428716
user1428716

Reputation: 2136

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

Upvotes: 1

Mr. Polywhirl
Mr. Polywhirl

Reputation: 48600

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

Upvotes: 2

Related Questions