覆盖 Collections.sort()

Overriding Collections.sort()

我正在实施 Kruskal 算法来查找图的 MST,我需要为第一步对边进行排序。但是,我需要按权重而不是它们的索引号对边缘进行排序。我覆盖了 compareTo() 并且我的 WeightedEdge 实现了 Comparable,所以我不确定为什么它继续按索引而不是权重排序。有什么想法吗?

  private final int v;
  private final int w;
  private int distance;
  private int price;
  /**
  * Create a directed edge from v to w with given weight.
  */
  public WeightedDirectedEdge(int v, int w, int distance, int price) {
    this.v = v;
    this.w = w;
    this.distance = distance;
    this.price = price;
  }

  public int from(){
    return v;
  }

  public int to(){
    return w;
  }

  public int distance(){
    return distance;
  }
  public int price(){
    return price;
  }
  @Override
  public int compareTo(WeightedDirectedEdge other)
  {
    Integer dist1 = new Integer(distance);
    Integer dist2 = new Integer(other.distance);
    return dist1.compareTo(dist2);
  }
}```

如果您想按重量排序,则需要这样做:

@Override
public int compareTo(WeightedDirectedEdge other){
    return Integer.compare(w, other.w);
}

而不是使用距离:

  @Override
  public int compareTo(WeightedDirectedEdge other)
  {
    Integer dist1 = new Integer(distance);
    Integer dist2 = new Integer(other.distance);
    return dist1.compareTo(dist2);
  }

您无需执行 new Integer(distance); 即可使用 compareTo 只需使用 Integer.compare(..); 即可。