J2SE5.0新特性之Foreach

类别:Java 点击:0 评论:0 推荐:

J2SE5.0新特性之Foreach

晁岳攀 [email protected]

 

C#中提供了Foreach的用法:

foreach (string item in f)

{

   Console.WriteLine(item);

}

Java也增加了这样的功能:

package com.kuaff.jdk5;

 

import java.util.*;

import java.util.Collection;

 

 

public class Foreach

{

    private Collection<String> c = null;

    private String[] belle = new String[4];

    public Foreach()

    {

        belle[0] = "西施";

        belle[1] = "王昭君";

        belle[2] = "貂禅";

        belle[3] = "杨贵妃";

        c = Arrays.asList(belle);

    }

    public void testCollection()

    {

        for (String b : c)

        {

              System.out.println("曾经的风化绝代:" + b);

        }

    }

    public void testArray()

    {

        for (String b : belle)

        {

              System.out.println("曾经的青史留名:" + b);

        }

    }

    public static void main(String[] args)

    {

        Foreach each = new Foreach();

        each.testCollection();

        each.testArray();

    }

}

对于集合类型和数组类型的,我们都可以通过foreach语法来访问它。上面的例子中,以前我们要依次访问数组,挺麻烦:

for (int i = 0; i < belle.length; i++)

{

        String b = belle[i];

        System.out.println("曾经的风化绝代:" + b);

}

现在只需下面简单的语句即可:

for (String b : belle)

{

       System.out.println("曾经的青史留名:" + b);

 }

对集合的访问效果更明显。以前我们访问集合的代码:

for (Iterator it = c.iterator(); it.hasNext();)

{

        String name = (String) it.next();

        System.out.println("曾经的风化绝代:" + name);

}

现在我们只需下面的语句:

for (String b : c)

{

        System.out.println("曾经的风化绝代:" + b);

}

 

Foreach也不是万能的,它也有以下的缺点:

在以前的代码中,我们可以通过Iterator执行remove操作。

for (Iterator it = c.iterator(); it.hasNext();)

{

       itremove()

}

 

但是,在现在的foreach版中,我们无法删除集合包含的对象。你也不能替换对象。

同时,你也不能并行的foreach多个集合。所以,在我们编写代码时,还得看情况而使用它。

 

本文地址:http://com.8s8s.com/it/it12736.htm