Search code examples
javacomparable

Overriding Collections.sort()


I'm implementing Kruskal's algorithm for finding the MST of a graph, and I need to sort the edges for the first step. However, I need to sort the edges by the weight, not their index number. I overrode compareTo() and my WeightedEdge implements Comparable, so I'm not sure why it continues to sort by index and not weight. Any ideas?

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

Solution

  • If you want to sort by weight than you need to do this:

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

    instead of using the distance:

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

    You do not need to do new Integer(distance); so that you can use compareTo just use Integer.compare(..); instead.