package javaee.china.cxp;
import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.Map.Entry;
import org.junit.Test; /** * 增强for循环 * jdk1.5以上才能支持 * 增加for循环只能用在数组或实现Iterable接口的集合上 * 增加for只适合取数据 */ public class Demo_5_for {
@Test public void demo5_1(){ /** * 增强for循环 数组实验 */ int[] arr = {1,2,3,4,5,6,7}; for (int i:arr) { System.out.println(i); } } /** * 增强for循环 数组赋值实验 * 证明增强for循环 无法赋值 只适合取数据 * 如果要赋值请使用传统的For循环 */ @Test public void demo5_1_1(){ int[] arr = {1,2,3,4,5,6,7}; for (int i:arr) { arr[i] = 10;//i为对象 无法当整醒数组 } for(int i:arr){ System.out.println(i); } } /** * 展示HashMap传统的存取方法一 */ @Test public void demo5_2(){ Map map = new HashMap(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); Set set = map.keySet(); Iterator it = set.iterator(); while(it.hasNext()){ String key = (String) it.next(); String value = (String) map.get(key); System.out.println(key+":"+value); } } /** * LinkedHashMap线性存储实验 * 个人认为LinkedHashMap 比 HashMap 更容易使用 因为存储顺序一样 */ @Test public void demo5_3(){ Map map = new LinkedHashMap();//LinkedHashMap属于线性列表 存取顺序一样 map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); Set set = map.keySet(); Iterator it = set.iterator(); while(it.hasNext()){ String key = (String) it.next(); String value = (String) map.get(key); System.out.println(key+":"+value); } } /** * 展示HashMap传统的存取方法二 */ @Test public void demo5_4(){ Map map = new HashMap(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); Set set = map.entrySet(); Iterator it = set.iterator(); while(it.hasNext()){ Map.Entry entry = (Entry) it.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key+":"+value); } } /** * 增强for循环 HashMap实验 * HashMap并没有实现Iterable接口 变相将其转换实现Iterable接口 * 展示HashMap传统的存取方法一 */ @Test public void demo5_5(){ Map map = new HashMap(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); Set set = map.keySet(); for(Object j:set){ String key = (String)j; String value = (String) map.get(key); System.out.println(key+":"+value); } /* while(it.hasNext()){ String key = (String) it.next(); String value = (String) map.get(key); System.out.println(key+":"+value); }*/ } /** * 增强for循环 HashMap实验 * HashMap并没有实现Iterable接口 变相将其转换实现Iterable接口 * 展示HashMap传统的存取方法二 */ @Test public void demo5_6(){ Map map = new HashMap(); map.put("1", "a"); map.put("2", "b"); map.put("3", "c"); map.put("4", "d"); Set set = map.entrySet(); for(Object j:set){ Entry entry = (Entry) j; String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key+":"+value); } }
}