我有下面的对象。
public class Coords {
public int x;
public int z;
public Coords(int x, int z) {
this.x = x;
this.z = z;
}
}
如何实现 Compareable? 我不确定 compareTo 方法应该做什么。
@Override
public int compareTo(Object o) {
// TODO Auto-generated method stub
return 0;
}
最佳答案
您可以比较 x
,然后比较 z
(或者,先比较 z
,然后比较 x
)。另外,我建议您覆盖 toString
。类似的东西,
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);
}
}
关于Java使自定义对象具有可比性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31352243/