體驗JDK1.5的特性一

 雖然jdk1.5已經發布很長時間了,由於公司整體產品的jdk並沒有進行同步升級,所以最近纔開始關注jdk1.5的一些新的特性.

1、泛型(generic)    

Collection<String> c = new ArrayList();
c.add(
new Date());

//此時編譯器便會提出編譯錯誤,此處只能add字符類型.

 2、增強的For循環

 

void processAll(Collection c)...{
    
for(Iterator i=c.iterator(); i.hasNext();)...{
        MyClass myObject 
= (MyClass)i.next();
        myObject.process();
    }
}

//使用For-Each循環,我們可以把代碼改寫成:
void processAll(Collection<MyClass> c)...{
    
for (MyClass  myObject :c)
        myObject.process();
}

 

3、自動裝箱/拆箱(Autoboxing/unboxing)

 

int a = 3;
Collection c 
= new ArrayList();
c.add(a);
//自動轉換成Integer.

Integer b 
= new Integer(2);
c.add(b 
+2);

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章