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?
If you check the
ArrayList.indexOf
implementation, you will see thatVector3i.equals
is called in your case. Actually it's even specified in JavaDoc forList
:In general
equals
operation must be symmetric:a.equals(b) == b.equals(a)
. So you have to implementVector3i.equals
as well.Please note also that your current
equals
implementation lacks other properties like reflexivity. Also consider implementing thehashCode
when you implement anequals
.