学习笔记:泛型数组
来源:互联网 发布:蜂窝移动数据怎么清零 编辑:程序博客网 时间:2024/06/14 07:10
public class Fruits<T> { private List<T> array=new ArrayList<T>(); public void add(T f){ array.add(f); } public T get(int index){ return array.get(index); }}
以上代码得到了数组类型,而且类型安全由泛型提供
public class FruitsReference {static Fruits<Integer>[] f;class Fruits<T>{}}
以上代码不会报错和产生任何警告,但永远不能创建这个确切类型的数组
public class Fruit1 { static final int SIZE=100; static Fruits<Integer>[] f; @SuppressWarnings("unchecked") public static void main(String[] args){ f=(Fruits<Integer> [])new Fruits[SIZE]; System.out.println(f.getClass().getSimpleName()); f[0]=new Fruits<Integer>(); //f[1]=new Object(); 这样做在编译期会报错,但数组f在运行时依然是Object数组 //f[2]=new Fruits<Double>(); }}
转型信息只存在于编译期,在运行时数组f依然是Object数组
public class FruitsArray<T> {private T[] array;@SuppressWarnings("unchecked")public FruitsArray(int sz){ array=(T[])new Object[sz];}public void put(int index,T item){ array[index]=item;}public T get(int index){ return array[index];}public T[] rep(){ return array;}public static void main(String[] args){ FruitsArray<Integer> fa=new FruitsArray<Integer>(10); //Integer[] ifu=fa.rep() 这会产生ClassCastException错误 Object[] of=fa.rep();}}
不能用Integer[]来捕获array,因为在运行时类型是Object[].
public class FruitsArray<T> {private T[] array;@SuppressWarnings("unchecked")public FruitsArray(int sz){ array=(T[])new Object[sz];}public void put(int index,T item){ array[index]=item;}public T get(int index){ return (T)array[index];}//添加泛型public T[] rep(){ return (T[])array;}//添加泛型public static void main(String[] args){ FruitsArray<Integer> fa=new FruitsArray<Integer>(10); //Integer[] ifu=fa.rep() 这仍然会产生ClassCastException错误 Object[] ofu=fa.rep();}}
成功创建泛型数组的唯一方式是创建一个被擦除类型的新数组,然后将其转型。
public class FruitsArray<T> {private T[] array;@SuppressWarnings("unchecked")public FruitsArray(Class<T> type,int sz){ array=(T[])new Object[sz];}public void put(int index,T item){ array[index]=item;}public T get(int index){ return array[index];}public T[] rep(){ return array;}public static void main(String[] args){ FruitsArray<Integer> fa=new FruitsArray<Integer>(Integer.class,10); Integer[] ifu=fa.rep() ;//现在可以这样做了}}
类型标记Class< T >被传递到构造器中,就可以从擦除中恢复
阅读全文
0 0
- 学习笔记:泛型数组
- Java学习笔记【泛型数组列表ArrayList】
- C++学习笔记--数组
- PHP学习笔记-数组
- java数组学习笔记
- 数组学习笔记
- PHP学习笔记-数组
- Javascript学习笔记-----数组
- 树状数组学习笔记
- 树状数组学习笔记
- 学习笔记----树状数组
- 后缀数组 学习笔记
- Java学习笔记--数组
- JS学习笔记-数组
- javase学习笔记------------数组
- php学习笔记--数组
- 后缀数组学习笔记
- JavaScript学习笔记:数组
- web测试-权限管理和兼容性测试
- raid5因两块硬盘掉线导致的数据丢失恢复过程分享
- Windows 10 1703/1709 版本 Win+X 丢失原控制面板解决方法
- 回调函数的作用
- Spring Security4.0.3源码分析之FilterChainProxy执行过程分析
- 学习笔记:泛型数组
- Paint.getTextBounds (String text, int start, int end, Rect bounds)
- android4.0 MediaPlayer的notify监听机制的全面剖析
- java开发中一些层或者结构的知识
- [JAVA学习笔记-78]lockInterruptibly
- Java中Calendar类的使用
- 享元模式Flyweight(结构型)
- 设计模式之原型模式
- java中condition使用遇到的问题