识别arraylist中的自定义对象

时间:2014-01-19 06:28:19

标签: java arraylist

我想检查对象Ball是否包含在ArrayList中。但每次我经历循环时,结果都给出了错误的答案。但我已经将对象球放在ArrayList中。不能这样做: - someList.contains(new Point(x,y))

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 个答案:

答案 0 :(得分:2)

你应该在Ball中实现equals。 Collection.contains使用equals。测试这个

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

它将返回false

答案 1 :(得分: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;
}