Transmission type variable when instantiating a class

Can someone explain what is different between the two instances of the class ArrayList?

List<Integer> intList = new  ArrayList();
List<Integer> intList = new  ArrayList<Integer>();

I knew that the compiler erases a type variable, i.e. Integerwhen compiles it into bytecode, and the above example works exactly the same. I wonder if there is any use at all for passing a variable of type ( Integer) on the right side, since it is already declared on the left? As far as I can find on the Internet, they all use the latter, but I see no reason why I should announce it twice on both sides.

+3
source share
3 answers

type , . , , .

List<String> stringList = new ArrayList<String>();
stringList.add("foo");
List<Integer> intList = new ArrayList(stringList); // Warning about unchecked conversion
int i = intList.get(0); // Oops, throws a ClassCastException

, , , .

+2

. - . - . , , , .

, ArrayList . :

  • - , .
  • , . ArrayList , List<Integer>. , .
+3

You probably need a difference between:

List intList = new  ArrayList();
List<Integer> intList = new  ArrayList<Integer>();

They are the same at runtime. But there are big differences in compilation time.

0
source

Source: https://habr.com/ru/post/1779708/


All Articles