posts - 195, comments - 34, trackbacks - 0, articles - 1

java泛型学习笔记

Posted on 2009-08-15 16:15 小强摩羯座 阅读(251) 评论(0)  编辑  收藏 所属分类: Java


generic points to List<String> , List is called raw type here, and <String> is the parametered type.

Generic's functions are :
1. remove type cast;
2. typesafe programming;

The key question of Generic:
1. the inheritance attribute of OO is not support: List<String> is not a type of List<Object>。

2. Collection<?> c: the parametered type is unknown. so you cant add elem into c.but you may get the elem in c and we know they are of type Object.

3、类型推断

static  < T >   void  fromArrayToCollection(T[] a, Collection  <  T  >  c)   

   
for  (T o : a)   
         c.add(o);  
//  correct  
      }
 
 }

  对这个方法参数化类型T,由定义数据a和Collection时传入的共同决定,它们可以使用相同类型,也可以使用不同类型,当类型不同时,它们必须有继承关系,类型推断时使用较高的那个。
4, when to use <?> or <T> :他们主要用在泛型方法,T相比?,它有名称,可多次使用来表达依赖关系。所以在不表达依赖关系的地方就应该使用?。它简单、灵活。

而且有趣的是,它们并非水火不容,反而可以精妙配合,如下:  

 

1  class Collections 
2
3  public static < T > void copy(List < T > dest, List < ? extends T > src) {  } 
4
5}
 

 

这个合作使得dest src 的依赖关系得以表达,同时让 src 的接纳范畴扩大了。假如我们只用泛型方法来实现:  

 

1  class Collections 
2
3   public static < T, S extends T > void copy(List < T > dest, List < S > src) {  } 
4
5}
 

 

那么S 的存在就显得有些不必要,有些不优雅。总的来说,通配符更简洁清晰,只要情况允许就应该首选。

5、由于普通数组是协变的,而GenricType由于List<String>不是List<Object>的子类型,所以它不能协变。可以使用?来new 一个数组。但是通常new完就要加元素,而?类型未知不可以产生对象的。所以最后使用Class<T> 类型做形参,实参用T.class就可以。这就是为什么Hibernate.load和get中会使用的.class的用法。比较新知识点是String.class就是Class<String>(String.class称字面类常量)。当传入Class<T> c 对象后,可以利用reflect来构造对象,并作状态设置。





只有注册用户登录后才能发表评论。


网站导航: