Enhanced for cyclic learning notes
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 {@ Testpublic void ArrayForEnhance () {int arr [] = {1, 2, 3}; for (int num: arr) {System. out. println ("num") ;}@testpublic 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 () is saved based on the algorithm. use LinkedHashMap () */@ Testpublic void MapForEnhance () {// Map map = new HashMap (); // Map map = new LinkedHashMap () Saved by the algorithm; // store the map in the order it is stored. put ("1", "aaa"); map. put ("2", "bbb"); map. put ("3", "ccc"); map. put ("4", "fff"); map. put ("5", "rrr");/** 1. traditional method 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. traditional method 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. use the enhanced for loop 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. use the enhanced for loop 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/** note the following when using an enhanced for loop: the enhanced for loop is only suitable for obtaining data */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 ));}}