Masudul
Masudul

Reputation: 21981

Generic array creation with diamond operator

Today, I faced an odd situation of generic array creation of Java 7. Take a look at following two statement.

 Map<String, String>[] hashArr= new HashMap[2]; // Compiles 

 Map<String, String>[] hashArr= new HashMap<>[2];// Does not compile

Here first statement compiles without diamond operator, if I put diamond operator or generic type at right side than it does not compiles. I faced same situation for all generic type, List<T>, Set<T>

Can anyone tell me, what is the reason for not compiles second statement?

Upvotes: 3

Views: 566

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201517

You cannot create a generic array of type HashMap in java due to type erasure (the generic(s) are erased by the compilation step). This code

Map<String, String>[] hashArr= new HashMap<String,String>[2]; // gives a better error.

Your first statement is an array of untyped HashMap, I know it compiles. Does it work?

To my delight, this does work

Map<String, String>[] hashArr = new HashMap[1];
hashArr[0] = new HashMap<>();                    // Your diamond sir.
hashArr[0].put("Hello", "World");
System.out.println(hashArr[0].get("Hello"));

Upvotes: 3

Related Questions