1. 程式人生 > >java Iterable and for each

java Iterable and for each

Java api

public interface Iterable<T>
Implementing this interface allows an object to be the target of the “for-each loop”, see java api

Example

public class IterableString implements Iterable<Character> {
    private String original;

    public IterableString(String original) {
        this
.original = original; } public Iterator<Character> iterator() { return new Iterator<Character>(){ 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