TreeMapのは正しく並べ替えません

user1986787:

私は、並べ替えしようとしていますTreeMapの「重量」によると。しかし、いくつかの理由では、キーが異なっていても同じ重み値を持つエントリを削除しています。

以下のコードは次のとおりです。

class Edge  {
    int source;
    int destination;
    int weight;

    public Edge(int source, int destination, int weight) {
        this.source = source;
        this.destination = destination;
        this.weight = weight;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + destination;
        result = prime * result + source;
        result = prime * result + weight;
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Edge other = (Edge) obj;
        if (destination != other.destination)
            return false;
        if (source != other.source)
            return false;
        if (weight != other.weight)
            return false;
        return true;
    }

    @Override
    public String toString() {
        return "Edge [source=" + source + ", destination=" + destination + ", weight=" + weight + "]";
    }
}

HashMapののデータ:

{エッジ[ソース= 0、宛先= 1、重量= 5] = 5、エッジ[ソース= 1、宛先= 2、重量= 4] = 4、エッジ[ソース= 2、目的地= 3、重量= 5] =図5に示すように、エッジ[ソース= 0、宛先= 3、重量= 6] = 6、エッジ[ソース= 0、宛先= 2、重量= 3] = 3、エッジ[ソース= 1、宛先= 3、重量= 7] = 7}

Map<Edge, Integer> treemap = new TreeMap<>(new MyWeightComp());
    treemap.putAll(map);

ツリーマップのコンパレータ:

 class MyWeightComp implements Comparator<Edge>{

    @Override
    public int compare(Edge e1, Edge e2) {
        return e1.weight-e2.weight;
    }
}

並べ替え後のデータ:

{エッジ[ソース= 0、宛先= 2、重量= 3] = 3、エッジ[ソース= 1、宛先= 2、重量= 4] = 4、エッジ[ソース= 0、宛先= 1、重量= 5] =図5に示すように、エッジ[ソース= 0、宛先= 3、重量= 6] = 6、エッジ[ソース= 1、宛先= 3、重量= 7] = 7}

あなたには、いくつかの理由で、同じ重みを持つデータは、キーが送信元と宛先の組み合わせであっても削除取得されていることがわかりますので。

ピーターLawrey:

すべてのマップの削除、重複してのcompareToは0を返した場合、同じキーであると仮定されます。

class MyWeightComp implements Comparator<Edge> {

    @Override
    public int compare(Edge e1, Edge e2) {
        int cmp = Integer.compare(e1.weight, e2.weight); // handle overflows.
        if (cmp == 0)
            cmp = Integer.compare(e1.source, e2.source);
        if (cmp == 0)
            cmp = Integer.compare(e1.destination, e2.destination);
        return cmp;
    }
}

あなたは、ソートのために重要ではないフィールドを持っている場合は、それらが重複する目的のために無視されたくない場合、あなたはまだ任意であるが、一貫した順序を選択する必要があります。

あなたが確認する必要があり、キーの一貫性があるcompare(a, b) == -compare(b, a)か、より正確にsign(compare(a, b)) == -sign(compare(b, a))

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=184481&siteId=1