Java ArrayList indexOf returns -1

Java ArrayList indexOf returns -1

我的代码有一个奇怪的问题。

这是我测试 Chunk class 的代码:

List<Chunk> chunks = new ArrayList<Chunk>();
chunks.add(new Chunk(1,1,1));
System.out.println(chunks.indexOf(new Vector3i(1, 1, 1)));

这是 Chunk class' 等于方法:

public boolean equals(Object object) {
    System.out.println("Test _1_");
    if (object != null && object instanceof Vector3i) {
        System.out.println("Test _2_");
        if((this.x == ((Vector3i) object).x)&&(this.y == ((Vector3i) object).y)&&(this.z == ((Vector3i) object).z)) {
            System.out.println("Test _3_");
            return true;
        }
    }
    System.out.println("Test _4_");

    return false;
}

Vector3i:

public class Vector3i {
    public int x;
    public int y;
    public int z;


    public Vector3i(int x, int y, int z) {
        this.x = x;
        this.y = y;
        this.z = z;
    }

}

当我运行它时,它只是returns-1。来自 equals 方法的测试打印不打印,这意味着它甚至没有开始执行。这是为什么?

如果你勾选 ArrayList.indexOf implementation, you will see that Vector3i.equals is called in your case. Actually it's even specified in JavaDoc for List:

More formally, returns the lowest index i such that (o==null ? get(i)==null : o.equals(get(i))), or -1 if there is no such index.

一般equals操作必须是对称的:a.equals(b) == b.equals(a)。所以你也必须实施Vector3i.equals

另请注意,您当前的 equals 实现缺少反身性等其他属性。在实施 equals.

时还应考虑实施 hashCode
chunks.indexOf(new Vector3i(1, 1, 1)

在 Vector3i class 上调用 equals() 方法,但是,不在 Chunk class...