注:以下示例均未使用泛型
方式一:(不推荐)
package test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class test {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
Iterator it = coll.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
方式二:(推荐,for循环结束后自动销毁Iterator对象)
package test;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class test {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
for (Iterator it = coll.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}
}
方式三:(推荐,高级for更简洁)
package test;
import java.util.ArrayList;
import java.util.Collection;
public class test {
public static void main(String args[]) {
Collection coll = new ArrayList();
coll.add("abc1");
coll.add("abc2");
coll.add("abc3");
/*
* foreach:增强for循环,用于遍历集合或数组,只能遍历读取元素,不可操作元素。
*/
for (Object object : coll) {
System.out.println(object);
}
}
}