j2se 1.5提供了另一种形式的for循环。借助这种形式的for循环,可以用更简单地方式来遍历数组和collection等类型的对象。本文介绍使用这种循环的具体方式,说明如何自行定义能被这样遍历的类,并解释和这一机制的一些常见问题。
在java程序中,要“逐一处理”——或者说,“遍历”——某一个数组或collection中的元素的时候,一般会使用一个for循环来实现(当然,用其它种类的循环也不是不可以,只是不知道是因为for这个词的长度比较短,还是因为for这个词的含义和这种操作比较配,在这种时候for循环比其它循环常用得多)。
对于遍历数组,这个循环一般是采取这样的写法:
清单1:遍历数组的传统方式
| /* 建立一个数组 */ int[] integers = {1, 2, 3, 4}; /* 开始遍历 */ for (int j = 0; j < integers.length; j++) { int i = integers[j]; system.out.println(i); } |
| /* 建立一个collection */ string[] strings = {"a", "b", "c", "d"}; collection stringlist = java.util.arrays.aslist(strings); /* 开始遍历 */ for (iterator itr = stringlist.iterator(); itr.hasnext();) { object str = itr.next(); system.out.println(str); } |
Java Asp PHP .Net XML C/C++ CGI VB Jsp J2ee J2se J2me EJB Servlet Tomcat Resin Struts Weblogic Eclipse ANT GUI JMS Web servise IDEA Webphere Hibernate Spring Jboss Applet Swing Socket Javamail Perl Ajax P2P 安全 模式 框架 测试 开源 游戏
Windows XP Windows 2000 Windows 2003 Windows Me Windows 9.x Linux UNIX 注册表 操作系统 服务器 应用服务器