代码示例:
public class TestIterator { //面试题: @Test public void testFor3() { String[] str = new String[]{"AA", "BB", "CC"}; for (String s : str) { //原理:将str中的每一个元素赋给String s,s是一个局部变量,s值的修改不会对str本身造成的影响 s = "MM"; System.out.println(s); } for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } @Test public void testFor2() { String[] str = new String[]{"AA", "BB", "CC"}; for (int i = 0; i < str.length; i++) { str[i] = i + ""; } for (int i = 0; i < str.length; i++) { System.out.println(str[i]); } } //*********************************************************************** //使用增强for循环实现数组的遍历 @Test public void testFor1() { String[] str = new String[]{"AA", "BB", "CC"}; for (String s : str) { System.out.println(s); } } //使用增强for循环实现集合的遍历 @Test public void test3() { Collection coll = new ArrayList(); coll.add(123); coll.add(new String("AA")); coll.add(new Date()); coll.add("BB"); coll.add(new Person("MM", 23)); for (Object i : coll) { System.out.println(i); } } //错误的写法:使用迭代器Iterator实现集合的遍历 @Test public void test2() { Collection coll = new ArrayList(); coll.add(123); coll.add(new String("AA")); coll.add(new Date()); coll.add("BB"); coll.add(new Person("MM", 23)); Iterator i = coll.iterator(); while ((i.next()) != null) { //java.util.NoSuchElementException System.out.println(i.next()); } } //正确的写法 @Test public void test1() { Collection coll = new ArrayList(); coll.add(123); coll.add(new String("AA")); coll.add(new Date()); coll.add("BB"); coll.add(new Person("MM", 23)); Iterator i = coll.iterator(); while (i.hasNext()) { System.out.println(i.next()); } } }面试题结果:
MM
MM
MM
AA
BB
CC
迭代器遍历示意图:
本文介绍了Java中遍历数组和集合的多种方法,包括增强for循环和迭代器的正确用法,并通过示例展示了不同遍历方式的效果及注意事项。

1552

被折叠的 条评论
为什么被折叠?



