Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing type variable when instantiating a generic class

Tags:

java

generics

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.

like image 281
gigadot Avatar asked Nov 21 '25 21:11

gigadot


1 Answers

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:

  • In other classes, the constructor may behave differently based on the specific type you're providing.
  • You'll make it easier on the compiler if you match the type. In the first version, the compiler will have to assign an object of type 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.
like image 64
EboMike Avatar answered Nov 23 '25 12:11

EboMike



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!