About the difference of list,map,set reference http://www.cnblogs.com/qlqwjy/p/7406573.html
1. Traversing the list
@Test Public voidtestlist () {List<Integer> list =NewArraylist<integer>(); List.add (1); List.add (2); System.out.println ("-------------------List------------------"); System.out.println ("-------Enhanced for loop list----"); for(inti:list) {System.out.println (i); } System.out.println ("-------for loop list----"); for(inti = 0; I < list.size (); i++) {System.out.println (List.get (i)); } System.out.println ("-------iterators traverse list----"); Iterator<Integer> iterator =List.iterator (); while(Iterator.hasnext ()) {System.out.println (Iterator.next ()); } }
Results:
-------------------list-------------------------enhanced for loop list-----------for loop list-----------iterator traverse list----12
2. Traverse the Map
@Test Public voidTestMap () {Map<integer, string> m =NewHashmap<integer, string>(); M.put (1, "s"); M.put (2, "s"); M.put (3, "s"); M.put (4, "s"); System.out.println ("-------------------Map------------------"); System.out.println ("--------Loop through key values---------"); for(Map.entry<integer, string>Entry:m.entryset ()) {System.out.println (Entry.getkey ()+ " " +Entry.getvalue ()); } System.out.println ("--------is based on the key value (the key is exactly an integer)---------"); for(inti = 0; I < m.size (); i++) {System.out.println (M.get (i+ 1)); } }
-------------------Map--------------------------Loop-through key values---------1 s 2 s3 s 4 s-----------------ssss based on the key value (the key is exactly an integer)
3. Traversing set
@Test Public voidTestset () {Set<Integer> set =NewHashSet (); Set.add (1); Set.add (2); System.out.println ("-------------------Set------------------"); System.out.println ("-------Enhance for loop----"); for(intI:set) {System.out.println (i); } System.out.println ("-------Iterator traversal----"); Iterator<Integer> iterator =Set.iterator (); while(Iterator.hasnext ()) {System.out.println (Iterator.next ()); } }
-------------------set-------------------------enhanced for loop-----------Iterator traversal----12
4. Traversing vectors
@Test Public voidTestvector () {System.out.println ("-------------------Vector------------------"); Vector<String> v =NewVector<string>(); V.add ("SSS"); V.add ("Sssss"); System.out.println ("-------normal for loop----"); for(inti = 0; I < v.size (); i++) {System.out.println (V.get (i)); } System.out.println ("-------Enhance for loop----"); for(String x:v) {System.out.println (x); } System.out.println ("-------Iterator traversal----"); Iterator<String> iterator =V.iterator (); while(Iterator.hasnext ()) {System.out.println (Iterator.next ()); } }
-------------------vector-------------------------normal for loop----ssssssss-------enhanced for loop----ssssssss -------Iterator traversal----ssssssss
Several methods of Java traversal List,map,vector,set