java 泛型详解
http://lichaozhangobj.iteye.com/blog/476911
泛型方法,这里的<T>指的是方法里面的泛型参数列表,因为在类定义里面没有给出参数,所以就在这里写。
泛型方法,因为在类定义里面已经给出了泛型参数列表<T>,所以在方法前面不用给出。
两者含义是一样的。
普通泛型
-
123456789101112131415161718192021222324252627282930313233343536373839404142434445Java代码class Point<T>{ // 此处可以随便写标识符号,T是type的简称private T var ; // var的类型由T指定,即:由外部指定public T getVar(){ // 返回值的类型由外部决定return var ;}public void setVar(T var){ // 设置的类型也由外部决定this.var = var ;}};public class GenericsDemo06{public static void main(String args[]){Point<String> p = new Point<String>() ; // 里面的var类型为String类型p.setVar("it") ; // 设置字符串System.out.println(p.getVar().length()) ; // 取得字符串的长度}};----------------------------------------------------------class Notepad<K,V>{ // 此处指定了两个泛型类型private K key ; // 此变量的类型由外部决定private V value ; // 此变量的类型由外部决定public K getKey(){return this.key ;}public V getValue(){return this.value ;}public void setKey(K key){this.key = key ;}public void setValue(V value){this.value = value ;}};public class GenericsDemo09{public static void main(String args[]){Notepad<String,Integer> t = null ; // 定义两个泛型类型的对象t = new Notepad<String,Integer>() ; // 里面的key为String,value为Integert.setKey("汤姆") ; // 设置第一个内容t.setValue(20) ; // 设置第二个内容System.out.print("姓名;" + t.getKey()) ; // 取得信息System.out.print(",年龄;" + t.getValue()) ; // 取得信息}};
通配符
受限泛型
泛型无法向上转型
泛型接口
泛型方法
通过泛型方法返回泛型类型实例
使用泛型统一传入的参数类型
泛型数组
泛型的嵌套设置
