美文网首页
java Iterable and for each

java Iterable and for each

作者: iamkai | 来源:发表于2016-11-18 17:57 被阅读0次

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

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

相关文章

网友评论

      本文标题:java Iterable and for each

      本文链接:https://www.haomeiwen.com/subject/pqlspttx.html