Java 的 自定义Iterable
等级 5282 次按键
通过匿名Iterator实现Iterable,使自定义对象可以用在for-each循环中。
Java 代码
// 实现了Iterable的类可以放在for-each循环的右侧1class Countdown implements Iterable<Integer> { // for-each循环会调用一次iterator()来获取一个新的Iterator2 public java.util.Iterator<Integer> iterator() { // 用匿名类实现Iterator;菱形<>会推断出Integer3 return new java.util.Iterator<>() { // 迭代器保存自己的状态:下一个要返回的数4 int n = 3; // hasNext()告诉循环是否还有更多元素5 public boolean hasNext() { return n > 0; } // next()返回当前值,然后n--为下一次调用将其减一6 public Integer next() { return n--; }7 };8 }9}// 遍历一个新的Countdown,输出3、2、110for (int x : new Countdown()) System.out.println(x);运行结果
3 2 1
可以用这段代码练习打字。成绩不会计入排行榜。
这段代码中的符号
这段 Java 代码中需要输入的符号及其出现次数。
(× 7)× 7.× 6;× 5{× 5}× 5>× 4<× 3-× 2:× 1