Java的:如何通用擦除工作原理 [英] Java :How Generic Erasure Works

查看:129
本文介绍了Java的:如何通用擦除工作原理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


  

情景A.java -----------擦除之后--------> M.class


  
  

情景B.java -----------擦除之后--------> M.class


那么,为什么A是非法的,B是合法的,因为他们几乎后删除。同样的中号

场景A擦除前:

 类的ArrayList< V> {
 私人V [] backingArray;
         公众的ArrayList(){
             backingArray =新的V [DEFAULT_SIZE]; //非法
           }
 }

场景A擦除之后:

 类的ArrayList< V> {
   私有对象[] backingArray;
      公众的ArrayList(){
      backingArray =新对象[DEFAULT_SIZE]; //这是没有用的
   }
}

实际上对象[DEFAULT_SIZE]是很有用的〜
方案B擦除前:

 类的ArrayList< V> {
  私人V [] backingArray;
  公众的ArrayList(){
    backingArray =(V [])新对象[DEFAULT_SIZE];
  }
}

擦除之后场景B:

 类的ArrayList< V> {
  私有对象[] backingArray;
  公众的ArrayList(){
    backingArray =(对象[])新对象[DEFAULT_SIZE];
  }
}


解决方案

的原因,方案A是非法的是,Java的协变阵列的的通过擦除实现的。这样的:

 对象[]富=新的String [4];
富[0] =新的对象();

将引发 ArrayStoreException信息 在运行时,因为指的是阵列实例的知道的它是一个的String [] (即使它是通过变量,其中有编译时类型对象简称[] )。因此,这:

 新的V [4]

是非法的,因为在运行时不知道要建立什么类型的数组实例。

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.

这篇关于Java的:如何通用擦除工作原理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆