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、類型推斷
對這個方法參數化類型T,由定義數據a和Collection時傳入的共同決定,它們可以使用相同類型,也可以使用不同類型,當類型不同時,它們必須有繼承關系,類型推斷時使用較高的那個。 4, when to use <?> or <T> :他們主要用在泛型方法,T相比?,它有名稱,可多次使用來表達依賴關系。所以在不表達依賴關系的地方就應該使用?。它簡單、靈活。
而且有趣的是,它們并非水火不容,反而可以精妙配合,如下:
這個合作使得dest 與 src 的依賴關系得以表達,同時讓 src 的接納范疇擴大了。假如我們只用泛型方法來實現:
那么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來構造對象,并作狀態設置。
Powered by: BlogJava Copyright © 小強摩羯座