Iterable接口实现 1.Iterable包含一个生成Iterator的iterator()方法,并且可使用Foreach遍历。2.必须要实现iterator()方法,并且要实现iterator的hasNext和next方法 IterablerImpl.java package com.demo;import java
1.Iterable包含一个生成Iterator的iterator()方法,并且可使用Foreach遍历。 2.必须要实现iterator()方法,并且要实现iterator的hasNext和next方法IterablerImpl.java
package com.demo; import java.util.Iterator; public class IterablerImplimplements Iterable { private T[] t = null; public IterablerImpl(T[] t) { this.t = t; } @Override public Iterator iterator() { return new Iterator () { private Integer index = 0; @Override public boolean hasNext() { return index < t.length; } @Override public T next() { return t[index++]; } }; } public static void main(String[] args) { IterablerImpl iterablerImpl = new IterablerImpl (new String[]{"hello", "world"}); for (String string : iterablerImpl) { System.out.println(string); } } }