目錄
集合的四種輸出方式:Iterator、ListIterator、Enumeration、foreach,其中Iterator使用的最多。
1、Iterator迭代輸出接口(核心)
Iterator是集合輸出中最標準的操作接口,開發中首選的就是Iterator,若想取得Iterator示例化對象,觀察Iterator接口的定義結構
【舉例】:利用Iterator進行迭代輸出
List<String> all =new ArrayList<String>();
all.add("hello");
all.add("world");
all.add("nice");
Iterator<String> iterator = all.iterator();
while (iterator.hasNext()){
String s = iterator.next();
System.out.println(s);
}
注意:迭代輸出時不能使用集合中的remove()方法,而應使用Iterator的remove方法,否則可以測試下,報錯。
2、ListIterator雙向迭代輸出(瞭解)
大部分情況下輸出操作基本用Iterator,基本只輸出一次,若要實現雙向迭代,需要使用ListIterator,進行雙向迭代操作時,必須先進行由前向後的迭代,再進行由後向前的迭代(因爲指針++的設計),瞭解即可,基本不會用。
List<String> all =new ArrayList<String>();
all.add("hello");
all.add("world");
all.add("nice");
ListIterator<String> iterator = all.listIterator();
while (iterator.hasNext()){
String s = iterator.next();
System.out.println(s);
}
while (iterator.hasPrevious()){
String s = iterator.previous();
System.out.println(s);
}
3、枚舉輸出:Enumeration
JDK1.0開始提供,其結構定義如下:
Enumeration最早是爲Vector服務的,只有Vector提供了實例化Enumeration的方法,elements()。
Vector<String> all =new Vector<>();
all.add("hello");
all.add("world");
all.add("nice");
Enumeration<String> e = all.elements();
while (e.hasMoreElements()){
String s = e.nextElement();
System.out.println(s);
}
4、foreach輸出
JDK1.5後提供的foreach輸出形式除了可以支持數組輸出外,也支持集合集合輸出。該輸出方法也叫做增強型for循環。
List<String> all =new ArrayList<>();
all.add("hello");
all.add("world");
all.add("nice");
for (String s:all){
System.out.println(s);
}
初學者不建議使用這種方式進行操作。
5、總結
1)集合輸出首先想到Iterator接口接口;
2)如果在必須的情況下使用Enumeration接口;