java46

1.迭代器遍历

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

public class 迭代器遍历 {
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void main(String[] args) {
    Collection c = new ArrayList();
    c.add("a");
    c.add("b");
    c.add("c");
//  遍历集合
    //1.数组
    Object[] o = c.toArray();
    for(int i=0;i<o.length;i++)
    {
        System.out.println(o[i]);
    }
    System.out.println("-------------------");
    //2.迭代器遍历
    Iterator it = c.iterator();
    Object obj = it.next();
    System.out.println(obj);
    Object obj2 = it.next();
    System.out.println(obj2);
    //判断集合中是否还有元素
    boolean res = it.hasNext();
    System.out.println(res);
    Object obj3 = it.next();
    System.out.println(obj3);

    Object obj4 = it.next();
    System.out.println(obj4);//没有元素了,会报错
    
}
}
【a
b
c
-------------------
a
b
true
c
Exception in thread "main" java.util.NoSuchElementException
    at java.util.ArrayList$Itr.next(ArrayList.java:862)
    at _07集合.迭代器遍历.main(迭代器遍历.java:34)】

```
Iterator it = c.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
【a
b
c】

猜你喜欢

转载自www.cnblogs.com/-zero/p/11366366.html