当前页面: 开发资料首页 → J2SE 专题 → J2SE5.0新特性之Foreach
J2SE5.0新特性之Foreach
摘要: J2SE5.0新特性之Foreach
showbanner(6,6,1);
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";
<iframe name="google_ads_frame" marginwidth="0" marginheight="0" src="http://pagead2.googlesyndication.com/pagead/ads?client=ca-pub-2141342037947367&dt=1117553238625&lmt=1117553238&prev_fmts=468x60_pas_abgnc&format=120x240_as&output=html&channel=8570654326&url=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fshowarticle.jsp%3Fcolumn%3D545&thread%3D19880&color_bg=FFFFFF&color_text=333333&color_link=000000&color_url=666666&color_border=CCCCCC&ref=http%3A%2F%2Fwww.javaresearch.org%2Farticle%2Fallarticles.jsp%3Fstart%3D510&thRange%3D30&cc=476&u_h=768&u_w=1024&u_ah=740&u_aw=1024&u_cd=16&u_tz=480&u_java=true" frameborder="0" width="120" scrolling="no" height="240" allowtransparency="65535"></iframe></td></tr></table></td></tr></table>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
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多个集合。所以,在我们编写代码时,还得看情况而使用它。