package com.lc.day01.ForEnhance; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import org.junit.Test; public class forEnhance { @Test public void ArrayForEnhance() { int arr[] = { 1, 2, 3 }; for (int num : arr) { System.out.println("num"); } } @Test public void ListForEnhance() { List list = new ArrayList(); list.add(1); list.add(2); list.add(3); list.add(4); for (Object obj : list) { int i = (Integer) obj; System.out.println(i); } } /* * 1.HashMap()是根据算法存的 2.如果需要按顺序存储的话使用LinkedHashMap() */ @Test public void MapForEnhance() { // Map map = new HashMap(); //根据算法存的 Map map = new LinkedHashMap(); // 按着自己存放的顺序 存储 map.put("1", "aaa"); map.put("2", "bbb"); map.put("3", "ccc"); map.put("4", "fff"); map.put("5", "rrr"); /* * 1.传统方式1 */ 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); } System.out.println("------------------------"); /* * 2.传统方式2 */ Set set1 = map.entrySet(); Iterator it1 = set1.iterator(); while (it1.hasNext()) { Map.Entry entry = (Entry) it1.next(); String key = (String) entry.getKey(); String value = (String) entry.getValue(); System.out.println(key + "=" + value); } System.out.println("------------------------"); /* * 3.利用增强for循环1 */ for(Object obj:map.keySet()){ String key = (String)obj; String value = (String)map.get(key); System.out.println(key + "=" + value); } System.out.println("------------------------"); /* * 4.利用增强for循环2 */ for(Object obj:map.entrySet()){ Map.Entry entry1 = (Entry)obj; String key = (String) entry1.getKey(); String value = (String) entry1.getValue(); System.out.println(key + "=" + value); } } @Test /* * 使用增强for循环要注意的事情:增强for循环只适合取数据 */ public void ForEnhancePoint(){ int arr[] = {1,2,3}; for(int i:arr){ i = 10; } System.out.println(arr[0]); System.out.println(arr[1]); System.out.println(arr[2]); List list = new ArrayList(); list.add("1"); for(Object obj:list){ obj = "10"; } System.out.println("--------------------"); System.out.println(list.get(0)); } }
原文地址:http://blog.csdn.net/xlgen157387/article/details/39272551