1 Iterator 的基本使用
迭代器统一了对集合的访问方式。注意迭代器在集合层次中的位置。
package com.hcong.collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
/**
* @Classname SimpleIteration
* @Date 2023/4/4 16:16
* @Created by HCong
*/
public class SimpleIteration {
public static void main(String[] args) {
// 1.迭代器遍历
Collection<Integer> collection = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
Iterator<Integer> it = collection.iterator();
while (it.hasNext()) {
Integer next = it.next();
System.out.print(next + " ");
}
System.out.println();
// 2.for-in
for (Integer i : collection) {
System.out.print(i + " ");
}
System.out.println();
// 3.迭代器删除元素
it = collection.iterator();
for (int i = 0; i < 5; i++) {
it.next();
it.remove();
}
System.out.println(collection);
}
}
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10
[6, 7, 8, 9, 10]
2 ListIterator 的基本使用
package com.hcong.collections;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ListIterator;
/**
* @Classname ListIteration
* @Date 2023/4/4 16:35
* @Created by HCong
*/
public class ListIteration {
public static void main(String[] args) {
List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C", "D", "E", "F", "G"));
ListIterator<String> lit = list.listIterator();
while (lit.hasNext()) {
String next = lit.next();
System.out.println(next + " " + lit.nextIndex() + " " + lit.previousIndex() + " ");
}
System.out.println();
}
}
A 1 0
B 2 1
C 3 2
D 4 3
E 5 4
F 6 5
G 7 6