1. List的两种遍历方式
package com.nova.test;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ListDemo {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("super");
list.add("nova");
list.add("supernova");
list.add("go");
// 通过Iterator的方式遍历
Iterator<String> iterator = list.iterator();
while (iterator.hasNext()) {
String str = iterator.next();
System.out.println(str);
}
list.add(1, "star");// 在1位置处添加元素
list.remove(list.size() - 1);// 删除列表最后一个元素
System.out.println("通过增强for循环遍历");
// 通过增强for循环遍历
for(String str:list) {
System.out.println(str);
}
}
}
2. Map的三种遍历方式
package com.nova.test;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map = new HashMap<Integer,String>();
//存放数据
map.put(1,"super");
map.put(2,"nova");
map.put(3,"supernova");
//通过Set遍历
System.out.println("通过Set遍历");
Set<Integer> set1 = map.keySet();
Iterator<Integer> iterator1 = set1.iterator();
while(iterator1.hasNext()) {
Integer id = iterator1.next();
System.out.println(id+" "+ map.get(id));
}
map.put(2,"star");//覆盖替换key为2的值
//通过EntrySet遍历
System.out.println("通过EntrySet遍历");
Set<Map.Entry<Integer,String>> set2 = map.entrySet();
Iterator<Map.Entry<Integer,String>> iterator2 = set2.iterator();
while(iterator2.hasNext()) {
Map.Entry<Integer,String> entry = iterator2.next();
System.out.println(entry.getKey()+" "+entry.getValue());
}
map.remove(1);//删除key为1的数
map.put(4,"hero");//添加数据
//通过增强for循环遍历
System.out.println("通过增强for循环遍历");
Set<Integer> set3 = map.keySet();
for(Integer num:set3) {
System.out.println(num+" "+map.get(num));
}
}
}