//code list 5 import Java.util.Hashtable; class Test { public static void main(String[] args) { Hashtable h = new Hashtable(); h.put("key", "value"); String s = (String)h.get("key"); System.out.println(s); } } 这个我们做了类型转换,是不是感觉很烦的,并且强制类型转换会带来潜在的危险,系统可能会抛一个ClassCastException异常信息。在JDK5.0中我们完全可以这么做,如:
//code list 6 import Java.util.Hashtable; class Test { public static void main(String[] args) { Hashtable<String,Integer> h = new Hashtable<String,Integer> (); h.put("key", new Integer(123)); int s = h.get("key").intValue(); System.out.println(s); } }
//Code list 7 public void autoBoxingUnboxing(int i) { ArrayList<Integer> L= new ArrayList<Integer>(); L.add(i); int a = L.get(0); System.out.println("The value of i is " + a); } 2.3 限制泛型中类型参数的范围
也许你已经发现在code list 1中的TestGen<K,V>这个泛型类,其中K,V可以是任意的型别。也许你有时候呢想限定一下K和V当然范围,怎么做呢?看看如下的代码:
//Code list 8 class TestGen2<K extents String,V extends Number> { private V v=null; private K k=null; public void setV(V v){ this.v=v; } public V getV(){ return this.v; } public void setK(K k){ this.k=k; } public V getK(){ return this.k; } public static void main(String[] args) { TestGen2<String,Integer> t2=new TestGen2<String,Integer>(); t2.setK(new String("String")); t2.setV(new Integer(123)); System.out.println(t2.getK()); System.out.println(t2.getV()); } } 上边K的范围是<=String ,V的范围是<=Number,注意是“<=”,对于K可以是String的,V当然也可以是Number,也可以是Integer,Float,Double,Byte等。看看下图也许能直观些请看上图A是上图类中的基类,A1,A2分别是A的子类,A2有2个子类分别是A2_1,A2_2。