迭代器
一个一个的拿出来。
package org.iterator;
import java.util.ArrayList;
import java.util.Iterator;
public class demo01 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("simple");
list.add("complex");
list.add("sim");
list.add("com");
System.out.println(list );
// 遍历list
for (int i = 0; i < list.size(); i++) {
String s = (String) list.get(i);
System.out.println(s);
}
// 创建迭代器
Iterator iterator = list.iterator();
String s1 = (String) iterator.next();
System.out.println(s1);
String s2 = (String) iterator.next();
System.out.println(s2);
String s3 = (String) iterator.next();
System.out.println(s3);
String s4 = (String) iterator.next();
System.out.println(s4);
}
}
常用方法
next()下一个
hasNext()是否存在下一个元素
迭代器循环遍历
package org.iterator;
import java.util.ArrayList;
import java.util.Iterator;
public class demo01 {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("simple");
list.add("complex");
list.add("sim");
list.add("com");
// 创建迭代器
Iterator iterator = list.iterator();
while (iterator.hasNext()){
String s = (String) iterator.next();
System.out.println(s);
}
}
}
遍历map
package org.iterator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class demo02 {
public static void main(String[] args) {
Map map = new HashMap();
map.put(1,"sim1");
map.put(2,"sim2");
map.put(3,"sim3");
map.put(4,"sim4");
// 方法一:
Set set = map.keySet();//拿到所有的key
Iterator it = set.iterator();
while (it.hasNext()){
int key = (int) it.next();//得到key
System.out.println(map.get(key));//得到value
}
// 方法二:
Set set1 = map.entrySet();
// entry就是key+value
Iterator it2 = set1.iterator();
while (it2.hasNext()){
Map.Entry entry = (Map.Entry) it2.next();
System.out.println(entry.getKey());
System.out.println(entry.getValue());
}
}
}