J2SE5.0新特性之Foreach

来源:互联网 发布:adobe旗下的软件 编辑:程序博客网 时间:2024/04/30 15:54

<script type="text/javascript">google_ad_client ="pub-2141342037947367";google_ad_width = 120;google_ad_height =240;google_ad_format = "120x240_as";google_ad_channel="8570654326";google_color_border = "CCCCCC";google_color_bg ="FFFFFF";google_color_link = "000000";google_color_url ="666666";google_color_text = "333333";</script><script src="http://pagead2.googlesyndication.com/pagead/show_ads.js" type="text/javascript"></script><iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2141342037947367&amp;dt=1117553238625&amp;lmt=1117553238&amp;prev_fmts=468x60_pas_abgnc&amp;format=120x240_as&amp;output=html&amp;channel=8570654326&amp;url=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fshowarticle.jsp%3Fcolumn%3D545%26thread%3D19880&amp;color_bg=FFFFFF&amp;color_text=333333&amp;color_link=000000&amp;color_url=666666&amp;color_border=CCCCCC&amp;ref=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fallarticles.jsp%3Fstart%3D510%26thRange%3D30&amp;cc=476&amp;u_h=768&amp;u_w=1024&amp;u_ah=740&amp;u_aw=1024&amp;u_cd=16&amp;u_tz=480&amp;u_java=true" frameborder="0" width="120" scrolling="no" height="240" allowtransparency="65535"></iframe>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多个集合。所以,在我们编写代码时,还得看情况而使用它。