[英]I try to use polymorphism but my code does not work as i excpected, could anyone help me solve this problem?
[英]Why polymorphism does not work as I'd expect in my code?
我对Java还是很陌生,遇到了一种奇怪的行为,我无法解释为什么会发生这种情况,或者代码中的错误在哪里。
这是代码:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
abstract class Shape {
public abstract void printMe(String no);
}
final class Circle extends Shape {
@Override
public void printMe(String no){
System.out.println("This is Circle no: " + no);
}
}
final class Square extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Square no: " + no);
}
}
final class Triangle extends Shape {
@Override
public void printMe(String no) {
System.out.println("This is Triangle no: " + no);
}
}
public class Foo {
private ArrayList<Shape> shapes;
public Foo(){
this.shapes = new ArrayList<Shape>();
this.shapes.add(new Circle());
this.shapes.add(new Square());
this.shapes.add(new Triangle());
}
public void printShapes(ArrayList<String> numbers){
for(String s:numbers){
Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);
}
}
public static void main(String[] args) {
ArrayList<String> numbers = new ArrayList<String>(Arrays.asList("1", "2", "3"));
Foo foo = new Foo();
foo.printShapes(numbers);
}
}
我期望的输出将是:
This is Circle no: 1
This is Square no: 2
This is Triangle no: 3
但是,我得到的输出是:
This is Circle no: 1
This is Circle no: 2
This is Circle no: 3
我究竟做错了什么?
将此行拉出循环:
Iterator<Shape> iter = this.shapes.iterator();
您总是得到一个新的迭代器-而不是使用相同的迭代器。
我不清楚我为什么仍然要这样做。 要么传递一个整数并循环直到它用完,要么遍历这些形状并保留一个计数器。 传递字符串数组使我感到笨拙。
public void printShapes() {
int i = 1;
for (Shape shape : shapes) {
shape.printMe(i++); // And modify the method to take an int.
}
}
我不满意形状需要知道的位置。 如果需要,请创建“ PositionalShape”之类的东西(但是ew),或者让形状输出可以与其他信息(例如列表位置)组合的字符串表示形式,或者创建形状装饰器等。
// (If you're really trying to print the first n shapes)
public void printShapes(int n) {
Iterator<Shape> iter = shapes.iterator();
for (int i = 0; i < n; i++) {
Shape shape = iter.next();
shape.printMe("" + i+1);
}
}
查看循环内的 Iterator<Shape> iter
。
public void printShapes(ArrayList<String> numbers){
for(String s:numbers){
Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);
}
}
您总是在抓住第一个形状(初始化迭代器,然后抓住)
我怀疑你需要在调试器中看到这个
Iterator<Shape> iter = this.shapes.iterator();
Shape shape = iter.next();
shape.printMe(s);
您每次都使用第一个共享(这是一个圈子)
您可以将iter
声明移到循环外进行修复。
以下两行必须处于循环状态: Shape shape = iter.next(); shape.printMe(s);
Shape shape = iter.next(); shape.printMe(s);
您总是重置迭代器:
Iterator<Shape> iter = this.shapes.iterator();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.