JDK1.5泛型之外的其它新特性,泛型相关看这里 For-Each循环 For-Each循环得加入简化了集合的遍历。假设我们要遍历一个集合对其中的元素进行一些处理。典型的代码为:
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循环,配合泛型,我们可以把代码改写成,
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. 枚举类型还提供了两个有用的静态方法values()和valueOf(). 我们可以很方便地使用它们,例如 for(Color c : Color.values()) System.out.println(c);
6.静态导入(Static Imports) 要使用用静态成员(方法和变量)我们必须给出提供这个方法的类。使用静态导入可以使被导入类的所有静 态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。 import static java.lang.Math.*; r = round(); //无需再写r = Math.round(); 不过,过度使用这个特性也会一定程度上降低代码地可读性
5.可变参数(Varargs) 可变参数使程序员可以声明一个接受可变数目参数的方法。注意,可变参数必须是函数声明中的最后一个参数。 假设我们要写一个简单的方法打印一些对象
例如:我们要实现一个函数,把所有参数中最大的打印出来,如果没有参数就打印一句话。 需求: prtMax(); prtMax(1); prtMax(1,2); prtMax(1,2,3); ...... prtMax(1,2,3...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
我们发先写多少个都不够,子子孙孙无穷尽也 改造一下,在上边的基础上,再加上 prtMax(int a,int b,int[] c){ //....比较最大的输出 这样能实现了,但是要求使用的人必须要在输入前把数字做成int[] } 看看现在使用新特性怎么实现:
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
好了,无论多少个参数都可以了 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);
|