简体   繁体   中英

Java :How Generic Erasure Works

Scenario A.java-----------after erasure-------->M.class

Scenario B.java-----------after erasure-------->M.class

Then why A is illegal and B is legal since they have almost the same M after erasure.

Scenario A before erasure:

 class ArrayList<V> {
 private V[] backingArray;
         public ArrayList() {
             backingArray = new V[DEFAULT_SIZE]; // illegal
           }
 }

Scenario A after erasure:

 class ArrayList<V> {   
   private Object[] backingArray;   
      public ArrayList() {
      backingArray = new Object[DEFAULT_SIZE]; // this is not useful   
   } 
}

actually the Object[Default_Size] is useful ~ Scenario B before erasure:

class ArrayList<V> {
  private V[] backingArray;
  public ArrayList() {
    backingArray = (V[]) new Object[DEFAULT_SIZE]; 
  }
}

Scenario B after erasure:

class ArrayList<V> {
  private Object[] backingArray;
  public ArrayList() {
    backingArray = (Object[]) new Object[DEFAULT_SIZE]; 
  }
}

The reason that Scenario A is illegal is that Java's covariant arrays are not implemented via erasure. This:

Object[] foo = new String[4];
foo[0] = new Object();

will raise an ArrayStoreException at run-time, because foo refers to an array instance that knows it's a String[] (even though it's referred to via the variable foo , which has compile-time type Object[] ). So this:

new V[4]

is illegal, because the run-time won't know what type of array instance to create.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM