你试一下下面的例子: class Sim<T>{ private T ob; public Sim(T s){ob=s;} public T getob(){return ob;} public void showType(){ System.out.println("Type of T is " + ob.getClass().getName()); } }class GenDemo{ public static void main(String[] args){ Sim<Integer>iOb; iOb=new Sim<Integer>(88); iOb.showType(); int v=iOb.getob(); System.out.println("value: "+v);
private T ob; public Sim(T s){ ob=s; } public T getob(){ return ob; } public void showType(){ System.out.println("Type of T is " + ob.getClass().getName()); } }
HashMap<K,V>
class Sim<T>{
private T ob;
public Sim(T s){ob=s;}
public T getob(){return ob;}
public void showType(){
System.out.println("Type of T is " + ob.getClass().getName());
}
}class GenDemo{
public static void main(String[] args){
Sim<Integer>iOb;
iOb=new Sim<Integer>(88);
iOb.showType();
int v=iOb.getob();
System.out.println("value: "+v);
Sim<String>StrOb;
StrOb=new Sim<String>("Generics Test");
StrOb.showType();
String str=StrOb.getob();
System.out.println("value: "+str);
}
}
如果你想看原例子的话就找它的中文版看看《Java J2SE 5 Edition 参考大全》清华大学出版社
感谢 yanruilin() 的例子!
import java.util.*;
/**
*
* @author Administrator
*/
public class TestHashMap<Key, Value>{
public HashMap<Key, Value> h=new HashMap<Key, Value>();
public void put(Key k, Value v) {
h.put(k,v);
}
public Value get(Key k) {
return h.get(k);
}
public static void main(String args[]){
// Sim<Integer>iOb;
// iOb=new Sim<Integer>(88);
Sim<String>iOb;
iOb=new Sim<String>("xxx...");
TestHashMap<String,Sim> t=new TestHashMap<String,Sim>();
t.put("key", iOb);
Sim b;
b = t.get("key");
b.showType();
}
}
class Sim <T>{
private T ob;
public Sim(T s){
ob=s;
}
public T getob(){
return ob;
}
public void showType(){
System.out.println("Type of T is " + ob.getClass().getName());
}
}