泛型类:

格式:类名<类型1,类型2,...>

例如:class FanXing<T>


泛型方法:

格式:修饰符 <泛型类型> 返回值类型  方法名(泛型类型 形参);

例如:public <E> void show(E e){ };


泛型接口:

把泛型定义在接口上,我们以前见过的 Collection  Set  等都是泛型接口。


示例代码:


package FanXingDemo;
// 泛型类的定义
class ObjTools<T>{
private T obj;

public void setObj(T obj){
this.obj = obj;
}

public T getObj(){
return this.obj;
}
// 泛型方法的定义 类上可以没有泛型 也可以和类的泛型不一样
public <E> void show(E e){
System.out.println(e);
}

}
class FanXingDemo{
public static void main(String[] args){
// 泛型类的使用
ObjTools<String> ot = new ObjTools<String>();

ot.setObj(new String("hello"));
String s = ot.getObj();
System.out.println(s);// hello
ot.setObj("world");
String s1 = ot.getObj();
System.out.println(s1);// world

ObjTools<Integer> ot1 = new ObjTools<Integer>();
ot1.setObj(1);
Integer i = ot1.getObj();
System.out.println(i); // 1
ot1.setObj(new Integer(2));
Integer ii = ot1.getObj();
System.out.println(ii); // 2


// 泛型方法的使用

//仅仅使用泛型方法时 定义类时可以不带泛型,
// 此处为了省事在泛型类中又定义了个泛型方法。
ObjTools<String> ot2 = new ObjTools<String>();
ot2.show(11); // 11
ot2.show("hello");//hello
ot2.show(true);// true


}
}