[英]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.