JDK5.0 new feature-Enhanced for loop

Source: Internet
Author: User

==============

Enhanced for Loop
Its underlying implementation is the use of iterator.
What containers can use enhanced for? -----------iterable

The disadvantage of enhanced for is that it can only be traversed and cannot be manipulated during traversal.

Enhanced for format
For (type reference: Container) {
}
--------------------------------------------
About iterating over a collection.
List
1.Iterator
2. Enhanced for
3. General for
4.ListIterator
Set
1. Enhanced for
2.Iterator
Map
1.keySet---Get a set view of all keys
2.entryset--get the set view of Key-value

==============

Iterating over a list

 PackageCn.itcast.fordemo;Importjava.util.ArrayList;ImportJava.util.Iterator;Importjava.util.List;ImportJava.util.ListIterator;ImportJava.util.Random;Importorg.junit.Test;//code is required//iterating over a list Public classDemo1 {//1. Using a traditional iterator@Test Public voiddemo1 () {List<Integer> list =NewArraylist<integer>();  for(inti = 0; I < 10; i++) {List.add (NewRandom (). Nextint (100)); }        //For (iterator<integer> it = List.iterator (); It.hasnext ();) {        //System.out.println (It.next ()); // }Iterator<Integer> it =List.iterator ();  while(It.hasnext ()) {System.out.println (It.next ()); }    }    //2.----Benefits of using Listiterator: 1. You can traverse 2 down or up. The add set operation can be performed during traversal .@Test Public voidDemo2 () {List<Integer> list =NewArraylist<integer>();  for(inti = 0; I < 10; i++) {List.add (NewRandom (). Nextint (100)); } listiterator<Integer> it =List.listiterator ();  while(It.hasnext ()) {System.out.println (It.next ()); }    }    //3. Use normal for size get@Test Public voidDemo3 () {List<Integer> list =NewArraylist<integer>();  for(inti = 0; I < 10; i++) {List.add (NewRandom (). Nextint (100)); }         for(inti = 0; I < list.size (); i++) {System.out.println (List.get (i)); }    }    //4. Enhanced for@Test Public voidDemo4 () {List<Integer> list =NewArraylist<integer>();  for(inti = 0; I < 10; i++) {List.add (NewRandom (). Nextint (100)); }         for(intn:list)        {System.out.println (n); }    }}

Iterating over a set set

 PackageCn.itcast.fordemo;ImportJava.util.HashSet;ImportJava.util.Iterator;ImportJava.util.Set;Importorg.junit.Test;//iterating over a set set Public classDemo2 {//iterators@Test Public voiddemo1 () {Set<String> set =NewHashset<string> ();//use hashcode with equals to maintain uniqueness.Set.add ("Def"); Set.add ("123"); Set.add ("ABC");  for(Iterator<string> it =set.iterator (); It.hasnext ();)        {System.out.println (It.next ()); }    }        //Enhanced for@Test Public voidDemo2 () {Set<String> set =NewHashset<string> ();//use hashcode with equals to maintain uniqueness.Set.add ("Def"); Set.add ("123"); Set.add ("ABC");  for(String s:set) {System.out.println (s); }    }}

Map traversal

 PackageCn.itcast.fordemo;ImportJava.util.HashMap;ImportJava.util.Map;ImportJava.util.Set;Importorg.junit.Test;//Map Traversal Public classDemo3 {//using keyset@Test Public voiddemo1 () {Map<string, string> map =NewHashmap<string, string>(); Map.put ("First", "AAAA"); Map.put ("Second", "BBBB"); Set<String> keys = Map.keyset ();//It's first,second in keys.         for(String key:keys) {System.out.println ("Key:" + key + "VALUE:" +Map.get (key)); }    }    //using EntrySet@Test Public voidDemo2 () {Map<string, string> map =NewHashmap<string, string>(); Map.put ("First", "AAAA"); Map.put ("Second", "BBBB"); Set<map.entry<string, string>> set =Map.entryset ();  for(Map.entry<string, string>Entry:set) {System.out.println (Entry.getkey ()+ "   " +Entry.getvalue ()); }    }}

Arrays can also be traversed using enhanced for

 Package Cn.itcast.fordemo; Import org.junit.Test;  Public class Demo4 {    @Test    //  arrays can also traverse public void using enhanced for     Demo () {        int[] arr={1,2,3,4,5};                  for (int  n:arr) {            System.out.println (n);     }}}

JDK5.0 new feature-Enhanced for loop

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.