例如以下的代码:
  String[] names = {"BadBoy","GoodBoy","HappyGirl","sadGirl"};
  for(String option: names) {
   System.out.println(option);
  }
程序会依次打印出字符串数组里的所有字串,在一般的JAVA书籍上好象从来看不到有讲这样的循环表示方法呀,是不是JDK1.5增加的新特性呢?如果哪位大侠能具体说一下怎么用就更好了,谢谢啦。

解决方案 »

  1.   

    JDK1.5新特性简介-请大家继续补充 
    常年在海区潜水,也出来给大家做点小贡献。这两天闲着无聊,试了一把JDK1.5。觉得挺好使的,就把它们贴出来一下,希望能为那些正想学习1.5的XDJM节省个几分钟学习时间。如果还有什么遗漏,请大家继续补充。“JDK1.5”(开发代号猛虎)的一个重要主题就是通过新增一些特性来简化开发,这些特性包括泛型,for-each 循环,自动装包/拆包,枚举,可变参数, 静态导入 。使用这些特性有助于我们编写更加清晰,精悍,安全的代码。下面我们简单介绍一下这些新特性。
    1.泛型(Generic)
    C++通过模板技术可以指定集合的元素类型,而Java在1.5之前一直没有相对应的功能。一个集合可以放任何类型的对象,相应地从集合里面拿对象的时候我们也不得不对他们进行强制得类型转换。猛虎引入了泛型,它允许指定集合里元素的类型,这样你可以得到强类型在编译时刻进行类型检查的好处。
    Collection<String> c = new ArrayList();
    c.add(new Date());
    编译器会给出一个错误,
    add(java.lang.String) in java.util.Collection<java.lang.String> cannot be applied to (java.util.Date)
    2.For-Each循环
    For-Each循环得加入简化了集合的遍历。假设我们要遍历一个集合对其中的元素进行一些处理。典型的代码为:
    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 >> Integer)
    自动拆包:包装类自动转为基本类型.(Integer >> int)
    在JDK1.5之前,我们总是对集合不能存放基本类型而耿耿于怀,现在自动转换机制解决了我们的问题。
    int a = 3;
    Collection c = new ArrayList();
    c.add(a);//自动转换成Integer.Integer b = new Integer(2);
    c.add(b + 2);
    这里Integer先自动转换为int进行加法运算,然后int再次转换为Integer.
    4.枚举(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);5.可变参数(Varargs)
    可变参数使程序员可以声明一个接受可变数目参数的方法。注意,可变参数必须是函数声明中的最后一个参数。假设我们要写一个简单的方法打印一些对象,
    util.write(obj1);
    util.write(obj1,obj2);
    util.write(obj1,obj2,obj3);

    在JDK1.5之前,我们可以用重载来实现,但是这样就需要写很多的重载函数,显得不是很有效。如果使用可变参数的话我们只需要一个函数就行了
    public void write(Object... objs) {
    for (Object obj: objs)
    System.out.println(obj);
    }
    在引入可变参数以后,Java的反射包也更加方便使用了。对于c.getMethod("test", new Object[0]).invoke(c.newInstance(), new Object[0])),
    现在我们可以这样写了c.getMethod("test").invoke(c.newInstance()),这样的代码比原来清楚了很多。 
    6.静态导入(Static Imports)
    要使用用静态成员(方法和变量)我们必须给出提供这个方法的类。使用静态导入可以使被导入类的所有静态变量和静态方法在当前类直接可见,使用这些静态成员无需再给出他们的类名。
    import static java.lang.Math.*;
    …….
    r = sin(PI * 2); //无需再写r = Math.sin(Math.PI);
      

  2.   

    The For-Each Loop Language Contents 
     --------------------------------------------------------------------------------
    Iterating over a collection is uglier than it needs to be. Consider the following method, which takes a collection of timer tasks and cancels them: 
    void cancelAll(Collection<TimerTask> c) {
        for (Iterator<TimerTask> i = c.iterator(); i.hasNext(); )
            i.next().cancel();
    }The iterator is just clutter. Furthermore, it is an opportunity for error. The iterator variable occurs three times in each loop: that is two chances to get it wrong. The for-each construct gets rid of the clutter and the opportunity for error. Here is how the example looks with the for-each construct: void cancelAll(Collection<TimerTask> c) {
        for (TimerTask t : c)
            t.cancel();
    }When you see the colon (:) read it as “in.” The loop above reads as “for each TimerTask t in c.” As you can see, the for-each construct combines beautifully with generics. It preserves all of the type safety, while removing the remaining clutter. Because you don't have to declare the iterator, you don't have to provide a generic declaration for it. (The compiler does this for you behind your back, but you need not concern yourself with it.) Here is a common mistake people make when they are trying to do nested iteration over two collections: List suits = ...;
    List ranks = ...;
    List sortedDeck = new ArrayList();// BROKEN - throws NoSuchElementException!
    for (Iterator i = suits.iterator(); i.hasNext(); )
        for (Iterator j = ranks.iterator(); j.hasNext(); )
            sortedDeck.add(new Card(i.next(), j.next()));Can you spot the bug? Don't feel bad if you can't. Many expert programmers have made this mistake at one time or another. The problem is that the next method is being called too many times on the “outer” collection (suits). It is being called in the inner loop for both the outer and inner collections, which is wrong. In order to fix it, you have to add a variable in the scope of the outer loop to hold the suit: // Fixed, though a bit ugly
    for (Iterator i = suits.iterator(); i.hasNext(); ) {
        Suit suit = (Suit) i.next();
        for (Iterator j = ranks.iterator(); j.hasNext(); )
            sortedDeck.add(new Card(suit, j.next()));
    }So what does all this have to do with the for-each construct? It is tailor-made for nested iteration! Feast your eyes: for (Suit suit : suits)
        for (Rank rank : ranks)
            sortedDeck.add(new Card(suit, rank));The for-each construct is also applicable to arrays, where it hides the index variable rather than the iterator. The following method returns the sum of the values in an int array: // Returns the sum of the elements of a
    int sum(int[] a) {
        int result = 0;
        for (int i : a)
            result += i;
        return result;
    }So when should you use the for-each loop? Any time you can. It really beautifies your code. Unfortunately, you cannot use it everywhere. Consider, for example, the expurgate method. The program needs access to the iterator in order to remove the current element. The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would cover the great majority of cases. 
    --------------------------------------------------------------------------------
    Copyright &copy; 2004 Sun Microsystems, Inc. All Rights Reserved. 
    Please send us comments and suggestions  Java Software