1 package com.shellway.javase; 2 import java.util.ArrayList; 3 import java.util.Collection; 4 import java.util.HashSet; 5 import java.util.Iterator; 6 import java.util.List; 7 import java.util.Map; 8 import java.util.Set; 9 import java.util.TreeMap; 10 11 import org.junit.Test; 12 13 public class TestCollection { 14 15 public static void print(Collection<? extends Object> c){ 16 Iterator<? extends Object> it = c.iterator(); 17 while (it.hasNext()) { 18 Object object = (Object) it.next(); 19 System.out.println(object); 20 } 21 } 22 23 @Test 24 public void demo1(){ 25 Set<String> set = new HashSet<String>(); 26 set.add("AAA"); 27 set.add("BBB"); 28 set.add("CCC"); 29 print(set); 30 31 //Set的第一种遍历方式:利用Iterator 32 Iterator<String> it1 = set.iterator(); 33 for (String ss : set) { 34 System.out.println(ss); 35 } 36 //Set的第一种遍历方式:利用foreach 37 for (String sss : set) { 38 System.out.println(sss); 39 } 40 41 42 List<String> list = new ArrayList<String>(); 43 list.add("DDDDD"); 44 list.add("EEEEE"); 45 list.add("FFFFF"); 46 print(list); 47 48 //List的第一种遍历方式:因为list有顺序,利用size()和get()方法获取 49 for (int i = 0; i < list.size(); i++) { 50 System.out.println(list.get(i)); 51 } 52 //List的第二种遍历方式:利用Iterator 53 Iterator<String> it = list.iterator(); 54 while (it.hasNext()) { 55 System.out.println(it.next()); 56 } 57 //List的第三种遍历方式:利用foreach 58 for (String s2 : list) { 59 System.out.println(s2); 60 } 61 62 63 Map<String,String> map = new TreeMap<String, String>(); 64 map.put("Jerry", "10000"); 65 map.put("shellway", "20000"); 66 map.put("Kizi", "30000"); 67 print(map.entrySet()); 68 //Map的第一种遍历方式:先获得key,再获得值value 69 Set<String> sett = map.keySet(); 70 for (String s : sett) { 71 System.out.println(s+":"+map.get(s)); 72 } 73 //Map的第二种遍历方式:获得键值对 74 for (Map.Entry<String, String> entry : map.entrySet()) { 75 System.out.println(entry.getKey()+" : "+entry.getValue()); 76 } 77 } 78 }