JDK1.5泛型之外的其它新特性,泛型相關看這里
For-Each循環(huán)
For-Each循環(huán)得加入簡化了集合的遍歷。假設我們要遍歷一個集合對其中的元素進行一些處理。典型的代碼為:
1
class Bean
{
2
public void run()
{
3
//
.
4
}
5
}
6
1
ArrayList list = new ArrayList();
2
list.add( new Bean());
3
list.add( new Bean());
4
list.add( new Bean());
5
6
for (Iterator ie = list.iterator(); list.hasNext();)
{
7
Bean bean = (Bean)ie.next();
8
bean.run();
9
10
}
11
12
使用For-Each循環(huán),配合泛型,我們可以把代碼改寫成,
1
ArrayList < Bean > list = new ArrayList < Bean > ();
2
list.add( new Bean());
3
list.add( new Bean());
4
list.add( new Bean());
5
6
for (Bean bean : list )
{
7
bean.run();
8
}
9
10
這段代碼要比上面清晰些,少寫些,并且避免了強制類型轉換。
2.枚舉(Enums)
JDK1.5加入了一個全新類型的“類”-枚舉類型。為此JDK1.5引入了一個新關鍵字enmu.
我們可以這樣來定義一個枚舉類型。
public enum Color{
Red,
White,
Blue
}
然后可以這樣來使用Color myColor = Color.Red.
枚舉類型還提供了兩個有用的靜態(tài)方法values()和valueOf(). 我們可以很方便地使用它們,例如
for(Color c : Color.values())
System.out.println(c);
6.靜態(tài)導入(Static Imports)
要使用用靜態(tài)成員(方法和變量)我們必須給出提供這個方法的類。使用靜態(tài)導入可以使被導入類的所有靜
態(tài)變量和靜態(tài)方法在當前類直接可見,使用這些靜態(tài)成員無需再給出他們的類名。
import static java.lang.Math.*;
r = round(); //無需再寫r = Math.round();
不過,過度使用這個特性也會一定程度上降低代碼地可讀性
5.可變參數(shù)(Varargs)
可變參數(shù)使程序員可以聲明一個接受可變數(shù)目參數(shù)的方法。注意,可變參數(shù)必須是函數(shù)聲明中的最后一個參數(shù)。
假設我們要寫一個簡單的方法打印一些對象
例如:我們要實現(xiàn)一個函數(shù),把所有參數(shù)中最大的打印出來,如果沒有參數(shù)就打印一句話。
需求:
prtMax();
prtMax(1);
prtMax(1,2);
prtMax(1,2,3);
......
prtMax(1,2,3...n);
以前的實現(xiàn)方式:
1
prtMax()
{
2
System.out.println( " no parameter " );
3
}
4
prtMax( int a)
{
5
System.out.println(a);
6
}
7
prtMax( int a, int b)
{
8
if (a > b)
{
9
System.out.println(a);
10
} else
{
11
System.out.println(b);
12
}
13
}
14
15
我們發(fā)先寫多少個都不夠,子子孫孫無窮盡也
改造一下,在上邊的基礎上,再加上
prtMax(int a,int b,int[] c){
//....比較最大的輸出
這樣能實現(xiàn)了,但是要求使用的人必須要在輸入前把數(shù)字做成int[]
}
看看現(xiàn)在使用新特性怎么實現(xiàn):
1
prtMax( int
nums)
{
2
if (nums.length == 0 )
{
3
System.out.println( " no parameter " );
4
} else
{
5
int maxNum = 0 ;
6
for ( int num :nums)
{
7
if (num > maxNum)
{
8
maxNum = num;
9
}
10
}
11
System.out.println(maxNum);
12
}
13
}
14
好了,無論多少個參數(shù)都可以了
prtMax();
prtMax(1);
prtMax(1,2);
prtMax(1,2,3,4,5,6,7,8, ....,n);
另外JDK1.5中可以像c中這樣用了
String str="dd";
int k =2;
System.out.printf("str=%s k=%d",str,k);