Iterator接口,具有两个方法:hasNext及next,hasNext用于判断是否有下一个元素,next用于获得下一个元素。
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TestIterator {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("aa");
list.add("bb");
list.add("cc");
for (Iterator<String> iter = list.iterator(); iter.hasNext();) {
String temp = iter.next();
System.out.println(temp);
}
}
}
Map<String, String> map = new HashMap<>();
map.put("A", "1");
map.put("B", "2");
map.put("C", "3");
Set<Map.Entry<String, String>> entries = map.entrySet();
for (Iterator<Map.Entry<String, String>> iter = entries.iterator(); iter.hasNext(); ) {
Map.Entry<String, String> next = iter.next();
System.out.println(next.getKey() + "--------------" + next.getValue());
}
网友评论