这是书上第11章持有对象里面的练习31题
(3)修改RandomShapeGenerator.java,使其成为一个Iterable。
这是LZ写的代码:
public class RandomShapeIterable implements Iterator<Shape> {
private Random rand = new Random(27);
private final int generateShapeNum;
public RandomShapeIterable( int generateShapeNum ) {
this.generateShapeNum = generateShapeNum;
}
public Iterator<Shape> iterator() {
return new Iterator<Shape>() {
private int num = 0;
public boolean hasNext() {
return num < generateShapeNum;
}
public Shape next() {
num++;
switch(rand.nextInt(3)) {
default:
case 0: return new Circle();
case 1: return new Square();
case 2: return new Triangle();
}
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public static void main(String[] args) {
for (Shape s : new RandomShapeIterable(10)) {
s.draw();
s.erase();
}
}
}
报错如下:
在下面是答案上的代码
class RandomShapeGenerator implements Iterable<Shape> {
private Random rand = new Random(47);
private final int quantity;
RandomShapeGenerator(int quantity) {
this.quantity = quantity;
}
public Iterator<Shape> iterator() {
return new Iterator<Shape>() {
private int count;
public boolean hasNext() {
return count < quantity;
}
public Shape next() {
++count;
return nextShape();
}
public void remove() { // Not implemented
throw new UnsupportedOperationException();
}
};
}
private Shape nextShape() {
switch (rand.nextInt(3)) {
default:
case 0:
return new Circle();
case 1:
return new Square();
case 2:
return new Triangle();
}
}
}
public class E31_IterableRandomShapeGenerator {
public static void main(String[] args) {
RandomShapeGenerator rsg = new RandomShapeGenerator(10);
for (Shape shape : rsg)
System.out.println(shape.getClass().getSimpleName());
}
}
好吧,撸主不明白的地方有两处:
一、为什么实现Iterable接口的类不用在类中实现hasNext()、next()、remove()的定义,
然而在内部类里实现后却能够运行?
二、撸主检查了一遍又一遍实在是找不到自己写的代码到底哪里出了错,我感觉明明就跟答案里的一样啊?
跪求大神指点啊!!!
答案是java.lang.Iterable,而楼主java.util.Iterator.
答案实现了那个接口的唯一的方法,而楼主没有实现那个接口的3个方法。