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】
posted @ 2019-08-16 23:51  不断寻找  阅读(171)  评论(0编辑  收藏  举报