java46

故事扮演 提交于 2019-11-27 14:09:00

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】

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!