I was reading this article on Java Generics and there it is mentioned that the constructor for an ArrayList
looks somewhat like this:
class ArrayLis
Your second example is incorrect. Type erasure does not imply globally casting everything to Object
. As you surmised, this hardly makes any sense. Instead, what type erasure does is (literally) the following (borrowed from Jon Skeet):
List list = new ArrayList();
list.add("Hi");
String x = list.get(0);
This block of code is translated to:
List list = new ArrayList();
list.add("Hi");
String x = (String) list.get(0);
Notice the cast to String
, not merely a vanilla Object
. Type erasure "erases" the types of generics and casts all objects therein to T
. This is a clever way to add some compile-time user-friendliness without incurring a runtime cost. However, as the article claims, this is not without compromises.
Consider the following example:
ArrayList li = new ArrayList();
ArrayList lf = new ArrayList();
It may not seem intuitive (or correct), but li.getClass() == lf.getClass()
will evaluate to true.