Java make custom object comparable? -
i have object below.
public class coords { public int x; public int z; public coords(int x, int z) { this.x = x; this.z = z; } }
how can implement compareable? im not sure compareto method should doing.
@override public int compareto(object o) { // todo auto-generated method stub return 0; }
you compare x
, compare z
(alternatively, z
, x
). also, suggest override tostring
. like,
public class coords implements comparable<coords> { public int x; public int z; public coords(int x, int z) { this.x = x; this.z = z; } @override public int compareto(coords o) { if (this.x == o.x) { if (this.z == o.z) { return 0; } return this.z < o.z ? -1 : 1; } return this.x < o.x ? -1 : 1; } @override public string tostring() { return string.format("{%d, %d}", x, z); } }
Comments
Post a Comment