Collection集合的遍历

题目要求:
用2种方法,遍历Collection集合中的元素。

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class Test {
    public static void main(String[] args) {
	Collection<String >  t= new HashSet<String>();//多态
	t.add("Good");
	t.add("Night");
	t.add("!");
	//方法一:使用增强的for循环
	for(String o:t){
		System.out.println(o);
	  }
	//方法二:使用迭代器
	Iterator<String> m=t.iterator();//iterator()方法可以得到Iterator对象
	while(m.hasNext()){//Iterator接口中的hasNext()方法返回迭代器中是否还有对象
	     string s=m.next();//next()方法返回迭代器中下一个对象;
		System.out.println(s+"\t");
	}
   }
}

猜你喜欢

转载自blog.csdn.net/qq_43747311/article/details/84798865