`

JDK1.5 泛型之外的其它新特性

    博客分类:
  • jdk
阅读更多
JDK1.5泛型之外的其它新特性,泛型相关看这里
  
For-Each循环
For-Each循环得加入简化了集合的遍历。假设我们要遍历一个集合对其中的元素进行一些处理。典型的代码为:


   class  Bean  {
    public   void  run()  {
   // .
   }
}
 


  ArrayList list  =   new  ArrayList();
list.add( new  Bean());
list.add( new  Bean());
list.add( new  Bean());
 
   for (Iterator ie = list.iterator(); list.hasNext();)  {
  Bean bean  =  (Bean)ie.next();
  bean.run();
 
}
 

使用For-Each循环,配合泛型,我们可以把代码改写成,


  ArrayList < Bean >  list  =   new  ArrayList < Bean > ();
  list.add( new  Bean());
  list.add( new  Bean());
  list.add( new  Bean());
  
   for (Bean bean : list )  {
   bean.run();
  }
  
 
这段代码要比上面清晰些,少写些,并且避免了强制类型转换。
  
  
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);
以前的实现方式:


    prtMax()  {
   System.out.println( " no parameter " );
}
  prtMax( int  a)  {
   System.out.println(a);
  }
   prtMax( int  a, int  b)  {
     if (a > b)  {
    System.out.println(a);
   } else  {
   System.out.println(b);
  }
}
   
 
我们发先写多少个都不够,子子孙孙无穷尽也
改造一下,在上边的基础上,再加上
prtMax(int a,int b,int[] c){
//....比较最大的输出
这样能实现了,但是要求使用的人必须要在输入前把数字做成int[]
}
看看现在使用新特性怎么实现:


    prtMax( int   nums)  {
     if (nums.length == 0 )  {
    System.out.println( " no parameter " );
    } else  {
    int  maxNum  =   0 ;
      for ( int  num :nums)  {
       if (num  > maxNum)  {
      maxNum  =  num;
     }
   }
   System.out.println(maxNum);
  }
}
 
好了,无论多少个参数都可以了
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);

分享到:
评论
1 楼 dreamstone 2007-02-13  
建议,转载文章至少应该写个出处吧,这样做也是对作者的尊重。

相关推荐

Global site tag (gtag.js) - Google Analytics