泛型 :

参数化的类或者接口

1.指定的类型必须是类或者接口,不能是基本数据类型

2.泛型是作为参数在类或者接口的声明中定义

class A<T> {…}

命名规则

E  元素,集合类中常用

K  键

N  数字

T  类型

V  值

一般泛型:

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>();     t.setKey("汤姆") ;  // 设置第一个内容         t.setValue(20) ;   // 设置第二个内容         System.out.print("姓名;" + t.getKey()) ;  // 取得信息         System.out.print(",年龄;" + t.getValue()) ;  // 取得信息     
  }   
}; 

泛型方法

public class Util {  
  // Generic static method  
  public static <K, V> boolean compare(Pair<K, V> p1, Pair<K, V> p2) {  
    return p1.getKey().equals(p2.getKey())  
             && p1.getValue().equals(p2.getValue());  
  }  
} 

类型限定 :

继承限定 class A <T extends B>{....}  这里extedns可以是类,可以是接口

用途:

泛型必须是类或接口,不能是基本数据类型.,泛型对象之间不能使用算术运算符合

public static <T extends Comparable<T>> int countGreaterThan(T[] anArray, T elem) {  
  int count = 0;  
  for (T e : anArray)  
    if (e.compareTo(elem) > 0)  
      ++count;  
  return count;  
}

通配符:

上限通配符 

 public static void process(List<? extends Foo> list) { }

无限制通配符 List<?>

下限通配符 class A< T super S>{…}