type erasure in implementation of ArrayList in Java

前端 未结 3 1394
自闭症患者
自闭症患者 2021-02-08 00:16

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         


        
3条回答
  •  半阙折子戏
    2021-02-08 01:01

    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.

提交回复
热议问题