Can someone explain what the different between these two instantiations of the ArrayList class?
List<Integer> intList = new ArrayList();
List<Integer> intList = new ArrayList<Integer>();
I knew that the compiler erase the type variable, i.e. Integer, when compile it to bytecode and the above example both works exactly the same. I wonder if there is any benefit at all to pass the type variable (Integer) on the right hand side since it is already declared on the left? As far as I can find on the web, they all uses the latter one but I cannot see any reason why I should declare it twice on both sides.
They're two different things. The left side is the type of your variable. The right side is the type of the object you're creating. The compiler will first create the object using the type you gave it on the right side, then assign the reference to the variable on your left side.
In your case, there is no difference since an ArrayList has the same constructor in all cases. However:
ArrayList to a variable that expects a List<Integer> type. In some cases, you may get a warning because the types don't clearly match up.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With