foreach and iterators

Source: Internet
Author: User
Tags iterable

foreach and iterators

The foreach statement can be used for iterating over arrays and collections. It works because Java SE5 introduces a new interface called Iterable, which contains a iterator () method that produces iterator, and the Iterable interface is used by foreach to move through the sequence. So if you create any class that implements Iterable, you can use it in a foreach statement. --Java Programming thought 4th edition 11th Chapter 243 page

1. Any class that implements the Iterable interface can be used in a foreach statement.

1 //: Holding/iterableclass.java2 //anything iterable works with foreach.3 ImportJava.util.*;4 5  Public classIterableclassImplementsIterable<string> {6   protectedstring[] Words = ("and that's how" +7"We know the Earth to be banana-shaped."). Split ("");8    PublicIterator<string>iterator () {9     return NewIterator<string>() {Ten       Private intindex = 0; One        Public BooleanHasnext () { A         returnIndex <words.length; -       } -        PublicString Next () {returnwords[index++]; } the        Public voidRemove () {//Not implemented -         Throw Newunsupportedoperationexception (); -       } -     }; +   }     -    Public Static voidMain (string[] args) { +      for(String s:NewIterableclass ()) ASystem.out.print (S + "")); at   } -}/*Output: - And that's how we know the Earth to be banana-shaped. - *///:~

2.foreach implementation principle: The foreach statement is eventually converted to a call to the Iterator.next () and Iterator.hashnext () methods, which is another form of encapsulation of the iterator. Just as a user, the JDK masks these implementation details. We don't even know the existence of iterator. Look at the bytecode generated by the compilation:

Java code:

1 ImportJava.util.*;2  Public classIterable_eros {3 4      Public Static voidMain (string[] args) {5List<string> strings =NULL;6          for(String s:strings) {7         }8     }9     Ten}

Javap-c generated byte code:

1Compiled from "Iterable_eros.java"2  Public classIterable_eros {3    PublicIterable_eros ();4 Code:50: Aload_061:invokespecial #1//Method java/lang/object. " <init> ":7 () V84:return9 Ten    Public Static voidMain (java.lang.string[]); One Code: A0: Aconst_null -1: Astore_1 -2: Aload_1 the3:invokeinterface #2, 1//Interfacemethod Java/util/list.iterator: () Ljava/util/iterator; -8: astore_2 -9: Aload_2 -10:invokeinterface #3, 1//Interfacemethod Java/util/iterator.hasnext: () Z +15:ifeq 31 -18: Aload_2 +19:invokeinterface #4, 1//Interfacemethod Java/util/iterator.next: () Ljava/lang/object; A24:checkcast #5//class Java/lang/string at27: Astore_3 -28:Goto9 -31:return -}

foreach and iterators

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.