2014-01-19 66 views
1

我想檢查對象球是否包含在ArrayList或不。但每次我經歷循環時,結果都會給出錯誤的答案。但我已經把對象球放在了ArrayList。不能這樣做: - someList.contains(new Point(x,y))識別arraylist中的自定義對象

public class zbc { 

    ArrayList<Balls> balls; 
    public boolean somRandomFunction() { 

     if (balls.contains(new Ball(i, j, k))) { 
      System.out.println("-----------------true------------------"); 
      break; 
     } 
    } 

} 

public class Ball { 

    private int row, col; 

    // this is actually just a integer value used 
    // by game to draw various distinct color 
    private int color; 

    public Ball(int row, int col, int color) { 
     this.row = row; 
     this.col = col; 
     this.color = color; 
    } 

    public int row() { 
     return row; 
    } 

    public int col() { 
     return col; 
    } 

    public int color() { 
     return color; 
    } 

} 

回答

2

您應該在Ball中實現equals。 Collection.contains使用equals。測試此

boolean equals = new Ball(1,1,1).equals(new Ball(1,1,1)) 

它會返回false

+0

沒有幫助MCH我得到它的另一種方式, 如果(ball.get(i,j)> 0){(Ball ball:balls){ if flag = false; 休息; } } –

2

您需要實現equals(Object)方法所以Java知道如何匹配兩個Ball實例。

例如,

@Override 
public boolean equals(Object o) { 
    if (o == null || !o instanceof Ball) { 
     return false; 
    } 
    Ball otherBall = (Ball)o; 
    return row == otherBall.row && 
      col == otherBall.col && 
      color == otherBall.color && 
} 

編輯: 另外,不要忘記,如果實現equals(Object),你也應該實現hashCode()

@Override 
public int hashCode() { 
    final int prime = 31; 
    int result = 1; 
    result = prime * result + row; 
    result = prime * result + col; 
    result = prime * result + color; 
    return result; 
}