簡體   English   中英

Java使自定義對象可比嗎?

[英]Java make custom object comparable?

我有下面的目標。

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

以下是compareTo的詳細信息:

將此對象與指定的對象進行比較以獲得順序。 返回負整數,零或正整數,因為此對象小於,等於或大於指定對象。

我建議這樣的事情:

@Override
public int compareTo(Coords other) {
    return this.x == other.x ? (this.z == other.z ? 0 : this.z - other.z) : this.x - other.x

如果切換它們,可以使z更重要。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM