下面的代码演示了遍历Collection集合的6种方法,注意Collection集合的遍历远不止于增强for循环,和迭代器两种。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Stack;
public class ListTest {
public static void main(String[] args)
{
String[] s="Productivity is being able to do things that you were never able to do before".split(" ");
List<String> list = Arrays.asList(s);
//第一种方法用增强for循环。(这里List之所以能用增强for循环其原因在于它实现了Iterable接口)
for(String str:list){
System.out.print(str+" ");
}
System.out.println();
System.out.println("************");
//第二种方法用Iterator
Iterator<String> it = list.iterator();
while(it.hasNext()){
String next = it.next();
System.out.print(next+" ");
}
System.out.println();
System.out.println("************");
//第三种方法:LinkedList 既有栈(stack)的特点,又有队列(Queue),可以进行相关的遍历。
//栈遍历
LinkedList<String> list2=new LinkedList<>(list);//创建一个LinkeList包含list中的全部元素。
while(!list2.isEmpty()){
System.out.print(list2.removeFirst()+" ");
}
System.out.println();
System.out.println("************");
//队列遍历
LinkedList<String> list3=new LinkedList<>(list);
while(list3.peek() != null){
System.out.print(list3.poll()+" ");
}
System.out.println();
System.out.println("************");
//第四种方法把所有的Collection都可以当做Enumeration进行遍历,Collections.enumeration(c)
ArrayList<String> list4=new ArrayList<>(list);
Enumeration<String> e = Collections.enumeration(list4);
while(e.hasMoreElements()){
System.out.print(e.nextElement()+" ");
}
//第五种方法
System.out.println();
System.out.println("************");
for(int i=0;i<list4.size();i++){
System.out.print(list4.get(i)+" ");
}
System.out.println();
System.out.println("************");
//第六种方法:
while(!list4.isEmpty()){
int index=0;
System.out.print( list4.remove(index++)+" ");
}
}
}