Java Foundation 40 enhanced for loop (also called Foreach Loop)

Source: Internet
Author: User
Tags iterable

enhanced for loop is a new feature that jdk1.5 appears1. Enhance the function of the For loop

simplifies the writing format of iterators (note: Enhancing the For loop bottom or using an iterator traversal)

2. Enhanced for Loop format
 for (data type  variable name: traversed target) {}
3, enhance the scope of the For loop

If an Iterable interface is implemented or an array object can use the enhanced for loop

1 Package   com.dhb.pattern;2 3  import java.util.Iterator;4 5 /**6 * @author dshore/2018-6-87  *8  */9 classMyList Implements Iterable<string>{TenObject[] Arr=Newobject[Ten]; One     intindex=0;//Current Pointer A      Public voidAdd (Object o) { -arr[index++]=o; -     } the      PublicIterator<string>iterator () { -          -         return NewIterator<string> () {//New Iterator<string> (): Anonymous inner class Iterator interface, abstract cannot be directly new -             intCursor=0;//Pointers +             //Hasnext (), Next (), and remove () are all methods to implement new Iterator<string> () -              PublicBoolean hasnext () { +                 returncursor<index; A             } at              PublicString Next () { -  -                 return(String) arr[cursor++]; -             } -              Public voidRemove () { -                  in             } -};//end the sign of the anonymous inner class ";" to     } + } -  Public classDemo2 { the      Public Static voidMain (string[] args) { *MyList list=NewMyList (); $List.add ("Zhang San");Panax NotoginsengList.add ("John Doe"); -List.add ("Harry"); theList.add ("Zhao Liu"); +          for(Stringstring: List) { ASystem. out. Print (string+",");//results returned: Zhang San, John Doe, Harry, Zhao Liu, the         } +     } -}
4. Things to be aware of to enhance the For loop

1. The enhanced for loop is also obtained using an iterator, except that the fetch iterator is done by the JVM and does not require us to get an iterator, and the index is not allowed to use the set to modify the set element on the collection elements in the process of using the enhanced for loop to iterate through the elements
2. the iterator iterates over the elements and enhances the difference between the For loop: You can delete a collection element when iterating through an element, while an enhanced for loop iterates over the collection element, you cannot call the Remove method inside the iterator to delete the element
3. the difference between the normal for loop and the enhanced for loop: The normal for loop can have no variable target, and the enhanced for loop must have a variable target

5. Example
1 Package   com.dhb.pattern;2  3  import java.util.HashSet;4  /**5 * @author dshore/2018-6-86   *7   */8   Public classDemo3 {9       Public Static voidMain (string[] args) {Ten         //Collection OneHashset<string>Set=NewHashset<string>(); A          Set. Add ("Dog left"); -          Set. Add ("Iron Egg"); -          Set. Add ("wheezing Tenjin Dog"); the     -Iterator<string> it=Set. iterator ();//using iterators to traverse set collections -           while(It.hasnext ()) { -System. out. println (It.next ()); +          } -         +           for(String s:Set){//using enhanced for loop traversal ASystem. out. println (s); at          } -  -           //Array -          int[] arr={ A,2,5,0};  -           for(inti =0; i < arr.length; i++) {//normal for loop traversal -System. out. println (Arr[i]); in          } -          to           for(intI:arr) {//enhanced for Loop traversal +System. out. println (i); -          } the      } *}

Original Dshore

Author's homepage:http://www.cnblogs.com/dshore123/

Source:https://www.cnblogs.com/dshore123/p/9156896.html

Welcome reprint, reprint must explain the source. ( If this article is helpful to you, you can click on the lower right corner of the recommendation , or comments, thank you!) )

Java Foundation 40 enhanced for loop (also called Foreach Loop)

Related Article

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.