码迷,mamicode.com
首页 > 编程语言 > 详细

数组泛型

时间:2017-05-15 13:01:47      阅读:264      评论:0      收藏:0      [点我收藏+]

标签:generic   order   content   turn   好的   one   ring   new   margin   

前言:大家都知道要定义如“T[]t = new T[10];”这样的泛型数组是不行的,自己也找了不少方法。最后在《Thinking InJava》中吸取了一种非常好的方法。

如今分享给大家。

 

?源代码:

  1. import java.lang.reflect.Array;
  2.  
  3. public classArrayOfGeneric<T> {
  4.  
  5.    T[]ts;
  6.  
  7.    @SuppressWarnings("unchecked")
  8.    publicArrayOfGeneric(Class<T> type, int size) {
  9.       ts = (T[]) Array.newInstance(type,size);
  10.    }
  11.  
  12.    public T get(int index) {
  13.       return ts[index];
  14.    }
  15.  
  16.    public T[] rep() {
  17.       return ts;
  18.    }
  19.  
  20.    public void set(int index, T t) {
  21.       ts[index] = t;
  22.    }
  23. }

 

?使用案例:

  1.    publicstaticvoidmain(String[] args) {   
  2.         ArrayOfGeneric<Integer> aog = newArrayOfGeneric<Integer>(Integer.class, 10);   
  3.         Object[] objs = aog.rep();   
  4.         for (int i = 0; i < 10; i++) {   
  5.             aog.set(i, i);
  6.             System.out.println(aog.get(i));   
  7.         }   
  8.         try {   
  9.             Integer[] strs =aog.rep();   
  10.             System.out.println("成功使用 Array.newInstance创建一个泛型数组!!!!! ");   
  11.         } catch (Exception ex) {   
  12.             ex.printStackTrace();   
  13.         }   
  14.     }   

 

 

 

如有好的建议,可留言或发至笔者邮箱:fzb_xxzy@163.com

 

数组泛型

标签:generic   order   content   turn   好的   one   ring   new   margin   

原文地址:http://www.cnblogs.com/gccbuaa/p/6855834.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!