A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© huangjiawei 中级黑马   /  2015-7-15 18:49  /  330 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

总结了一下泛型,比你脸上的毛孔还要细致
1.在集合中不使用泛型。
  1. public void test1(){
  2.         List list = new ArrayList();
  3.         list.add(89);
  4.         list.add(87);
  5.         list.add(67);
  6.         //1.没有使用泛型,任何Object及其子类的对象都可以添加进来
  7.         list.add(new String("AA"));
  8.        
  9.         for(int i = 0;i < list.size();i++){
  10.                 //2.强转为int型时,可能报ClassCastException的异常
  11.                 int score = (Integer)list.get(i);
  12.                 System.out.println(score);
  13.         }
  14. }
复制代码

2.在集合中使用了泛型
  1. public void test2(){
  2.         List<Integer> list = new ArrayList<Integer>();
  3.         list.add(78);
  4.         list.add(87);
  5. //                list.add("AA");
  6.        
  7. //                for(int i = 0;i < list.size();i++){
  8. //                        int score = list.get(i);
  9. //                        System.out.println(score);
  10. //                }
  11.         Iterator<Integer> it = list.iterator();
  12.         while(it.hasNext()){
  13.                 System.out.println(it.next());
  14.         }
  15. }

  16. public void test3(){
  17.         Map<String,Integer> map = new HashMap<>();
  18.         map.put("AA", 78);
  19.         map.put("BB", 87);
  20.         map.put("DD", 98);
  21.        
  22.         Set<Map.Entry<String,Integer>> set = map.entrySet();
  23.         for(Map.Entry<String,Integer> o : set){
  24.                 System.out.println(o.getKey() + "--->" + o.getValue());
  25.         }
  26. }
复制代码

3.自定义泛型类:应用
  1. public class DAO<T> {
  2.         public void add(T t){
  3.                 //....
  4.         }
  5.         public T get(int index){
  6.                 return null;
  7.         }
  8.         public List<T> getForList(int index){
  9.                 return null;
  10.         }
  11.         public void delete(int index){
  12.                
  13.         }
  14. }

  15. public class CustomerDAO extends DAO<Customer>{

  16. }

  17. public class TestCustomerDAO {
  18.         public static void main(String[] args) {
  19.                 CustomerDAO c = new CustomerDAO();
  20.                 c.add(new Customer());
  21.                 c.get(0);
  22.         }
  23. }
复制代码

【注意点】
1.对象实例化时不指定泛型,默认为:Object。
2.泛型不同的引用不能相互赋值。
3.加入集合中的对象类型必须与指定的泛型类型一致。
4.静态方法中不能使用类的泛型。
5.如果泛型类是一个接口或抽象类,则不可创建泛型  
  类的对象。
6.不能在catch中使用泛型
7.从泛型类派生子类,泛型类型需具体化


4.泛型与继承的关系
A类是B类的子类,G是带泛型声明的类或接口。那么G<A>不是G<B>的子类!

5.通配符:?
A类是B类的子类,G是带泛型声明的类或接口。则G<?> 是G<A>、G<B>的父类!
①以List<?>为例,能读取其中的数据。因为不管存储的是什么类型的元素,其一定是Object类的或其子类的。
①以List<?>为例,不可以向其中写入数据。因为没有指明可以存放到其中的元素的类型!唯一例外的是:null

6*.  List<? extends A> :可以将List<A>的对象或List<B>的对象赋给List<? extends A>。其中B 是A的子类
       ? super A:可以将List<A>的对象或List<B>的对象赋给List<? extends A>。其中B 是A的父类

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马