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、類型推斷
對(duì)這個(gè)方法參數(shù)化類型T,由定義數(shù)據(jù)a和Collection時(shí)傳入的共同決定,它們可以使用相同類型,也可以使用不同類型,當(dāng)類型不同時(shí),它們必須有繼承關(guān)系,類型推斷時(shí)使用較高的那個(gè)。 4, when to use <?> or <T> :他們主要用在泛型方法,T相比?,它有名稱,可多次使用來表達(dá)依賴關(guān)系。所以在不表達(dá)依賴關(guān)系的地方就應(yīng)該使用?。它簡(jiǎn)單、靈活。
而且有趣的是,它們并非水火不容,反而可以精妙配合,如下:
這個(gè)合作使得dest 與 src 的依賴關(guān)系得以表達(dá),同時(shí)讓 src 的接納范疇擴(kuò)大了。假如我們只用泛型方法來實(shí)現(xiàn):
那么S 的存在就顯得有些不必要,有些不優(yōu)雅。總的來說,通配符更簡(jiǎn)潔清晰,只要情況允許就應(yīng)該首選。 5、由于普通數(shù)組是協(xié)變的,而GenricType由于List<String>不是List<Object>的子類型,所以它不能協(xié)變。可以使用?來new 一個(gè)數(shù)組。但是通常new完就要加元素,而?類型未知不可以產(chǎn)生對(duì)象的。所以最后使用Class<T> 類型做形參,實(shí)參用T.class就可以。這就是為什么Hibernate.load和get中會(huì)使用的.class的用法。比較新知識(shí)點(diǎn)是String.class就是Class<String>(String.class稱字面類常量)。當(dāng)傳入Class<T> c 對(duì)象后,可以利用reflect來構(gòu)造對(duì)象,并作狀態(tài)設(shè)置。
Powered by: BlogJava Copyright © 小強(qiáng)摩羯座