集合类的各种实现类使用迭代器迭代的具体写法
enum Color {RED,
YELLOW;
}
public class T {
/**
* @param args
*/
public static void main(String[] args) {
HashSet<String> hashSet = new HashSet<String>();
System.out.println("HashSet的Iterator:" + hashSet.iterator()
);
LinkedHashSet<String> linkedHashSet = new LinkedHashSet<String>();
System.out.println("LinkedHashSet的Iterator:" +
linkedHashSet.iterator());
TreeSet<String> treeSet = new TreeSet<String>();
System.out.println("TreeSet的Iterator:" + treeSet.iterator());
EnumSet<Color> enumSet = EnumSet.allOf(Color.class);
System.out.println("EnumSet的Iterator:" + enumSet.iterator());
ArrayList<String> arrayList = new ArrayList<String>();
System.out.println("ArrayList的Iterator`这里写代码片`:" + arrayList.iterator());
Vector<String> vector = new Vector<String>();
System.out.println("Vector的Iterator:" + vector.iterator());
LinkedList<String> linkedList = new LinkedList<String>();
System.out.println("LinkedList的Iterator:" + linkedList.iterator());
ArrayDeque<String> arrayDeque = new ArrayDeque<String>();
System.out.println("ArrayDeque的Iterator:" + arrayDeque.iterator());
}
}
遍历输出方式(例如LinkedList())
第一种
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
第二种
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
Iterator<Integer> iterator = list.iterator();
for (; iterator.hasNext();) {
System.out.println(iterator.next());
}
}
第三种
public static void main(String[] args) {
List<Integer> list = new LinkedList<>();
for (int i = 0; i < 10; i++) {
list.add(i);
}
for (Iterator<Integer> it = list.iterator(); it.hasNext();) {
System.out.println(it.next());
}
}