2012-01-22 46 views
2

我對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 

我在做什麼錯誤?

回答

3

拉這條線圈外:

Iterator<Shape> iter = this.shapes.iterator(); 
1

你總是得到一個新的迭代器 - 而不是使用同一個。

不知道爲什麼你這樣做是這樣的;要麼傳遞一個整數並循環,直到它用完,要麼迭代形狀並保留一個計數器。傳遞一個字符串數組使我感到笨拙。

public void printShapes() { 
    int i = 1; 
    for (Shape shape : shapes) { 
     shape.printMe(i++); // And modify the method to take an int. 
    } 
} 

我很不舒服,需要注意它可以有一個位置的形狀。如果這是一個要求,創建一個「PositionalShape」或其他東西(但是新聞),或有形狀輸出一個字符串表示形式,可以與列表位置等附加信息合成,或創建一個形狀修飾符等。


// (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); 
    } 
} 
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); 
     } 
    } 

你總是抓住了第一個形狀(初始化迭代器,抓住下一個)

0

我懷疑你需要

Iterator<Shape> iter = this.shapes.iterator(); 
Shape shape = iter.next(); 
shape.printMe(s); 

看到這個在調試器但是,您正在使用的第一股每一次(這是一個循環)

您可以將iter聲明移到循環外部以修復它。

0

下面兩行需要在一個循環: Shape shape = iter.next(); shape.printMe(s);

0

你總是重置迭代器:

Iterator<Shape> iter = this.shapes.iterator(); 
相關問題