java Iterable and for each

Java api

public interface Iterable
Implementing this interface allows an object to be the target of the "for-each loop", see java api

Example

public class IterableString implements Iterable {
    private String original;

    public IterableString(String original) {
        this.original = original;
    }

    public Iterator iterator() {
        return new Iterator(){
            private int index;
            public boolean hasNext() {
                return index < original.length();
            }

            public Character next() {

                return Character.valueOf(original.charAt(index++));
            }

            public void remove() {}
        }; // end of return statement
    }

}

you can use for-each to iterate character like this.

for(Character c : str) {
    System.out.println(c);
}

if you decompile this java code, you will see the compiler do this thing.

Character c;
for(Iterator iterator = str.iterator(); iterator.hasNext();
  System.out.println(c))
    c = (Character)iterator.next();

Reference

  1. java.lang.Iterable Interface Example
  2. Iterator vs Foreach In Java
  3. 神奇的 foreach
  4. JavaSE8 API

你可能感兴趣的:(java Iterable and for each)