迭代器的使用

范例:

package cn.study.lu.four;

import java.util.*;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class TestIterator {
public static void main(String[] args) {
testIteratorList();
testIteratorSet();
testIteratotMap();
}




public static void testIteratorList() {
List list = new ArrayList();
list.add("aaa");
list.add("bbb");
list.add("ccc");
list.add("ddd");

for (Iterator iter = list.iterator();iter.hasNext();) {
String temp = iter.next();
System.out.println(temp);
}
}


public static void testIteratorSet() {
Set set = new HashSet();
set.add("111");
set.add("222");
set.add("333");
set.add("444");

for (Iterator iter = set.iterator();iter.hasNext();) {
String temp = iter.next();
System.out.println(temp);
}
}


public static void testIteratotMap() {
Map map1 = new HashMap();
map1.put(111, "aaa");
map1.put(222, "bbb");
map1.put(333, "ccc");
map1.put(444, "ddd");

/**/Set> ss = map1.entrySet();
//第一种遍历map的方式
for (Iterator> iter = ss.iterator();iter.hasNext();) {
Entry temp = iter.next();
System.out.println(temp.getKey()+"---"+temp.getValue());
}

System.out.println("--------------------------------------------");

//第二种遍历map的方式
Set keyset = map1.keySet();
for (Iterator iter = keyset.iterator();iter.hasNext();) {
Integer temp = iter.next();
System.out.println(temp+"---"+map1.get(temp));
}
}
}

你可能感兴趣的:(迭代器的使用)