Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 965
Masudul Avatar asked Feb 01 '26 01:02

Masudul


1 Answers

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"));
like image 100
Elliott Frisch Avatar answered Feb 03 '26 16:02

Elliott Frisch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!