Java ArrayList indexOf returns -1

245 views Asked by At

I have a strange problem with my code.

Heres the code I test the Chunk class with:

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

And here is the Chunk class' equals method:

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;
}

The 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;
    }

}

When I run it, it just returns -1. The test prints from the equals method doesn't print, which means that it's not even begin executed. Why is that?

2

There are 2 answers

2
Tagir Valeev On BEST ANSWER

If you check the 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.

In general equals operation must be symmetric: a.equals(b) == b.equals(a). So you have to implement Vector3i.equals as well.

Please note also that your current equals implementation lacks other properties like reflexivity. Also consider implementing the hashCode when you implement an equals.

0
Pavan Kumar K On
chunks.indexOf(new Vector3i(1, 1, 1)

calls equals() method on Vector3i class, howeve, not on Chunk class...