泛型讨论------危害的解决2

擦除失去了在泛型代码中执行某些操作的能力,任何在运行时需要知道确切类型信息的操作都将无法工作,看下面的例子:

 

public class Eras<T>{

	public static void main(String[] args){
		
		if(ages instanceof T){}//出错
		T var = new T();       //出错
		T[] array  =new T[100];//出错
		
	}
}

 

在例子中使用instanceof失败,因为它的类型已经被擦除了。

 

 

不能创建泛型数组,

如果想创建泛型数组,使用ArrayList,

 

public class ListOfGenerics<T>{

	private List<T> array = new ArrayList<T>();
	public void add(T item){
		array.add(item);
	}

	public T get(int idnex){
		retrun array.get(index);
	}
}

 

 

即使创建了数组

Dog<Integer>[] dog;

在编译器是没有问题的,但是在运行期仍然是个Object类型。

 

解决办法:

 

不能创建T[] array  = new T[sz];,可创建一个对象数组,将其转型

public class A{
	
	private T[] array;
	public A(int size){
		array = (T[])new Object[size];
	}
}

 

class Fruit {}
class Apple extends Fruit {}
class Jonathan extends Apple {}
class Orange extends Fruit {}

public class CovariantArrays {
  public static void main(String[] args) {
    Fruit[] fruit = new Apple[10];
    fruit[0] = new Apple(); // OK
    fruit[1] = new Jonathan(); // OK
    // Runtime type is Apple[], not Fruit[] or Orange[]:
    try {
      // Compiler allows you to add Fruit:
      fruit[0] = new Fruit(); // ArrayStoreException
    } catch(Exception e) { System.out.println(e); }
    try {
      // Compiler allows you to add Oranges:
      fruit[0] = new Orange(); // ArrayStoreException
    } catch(Exception e) { System.out.println(e); }
  }
} /* Output:
java.lang.ArrayStoreException: Fruit
java.lang.ArrayStoreException: Orange

 编译器允许放入Fruit对象,但这在运行时处理的却是Apple[]类型,错误就发生了,ArrayStoreException

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值