1

I have this piece of code which takes a Generic of type Comparable and my class implements Comparable Interface. I receive an error on compareTo() method in the class stating Comparable cannot be converted to T#1.

The complete error message is->

Edge.java:40: error: method compareTo in interface Comparable<T#2> cannot be applied to given types;    
    return (this.weight).compareTo(e.weight());
                        ^
    required: 
        T#1 found: Comparable reason: argument mismatch; Comparable cannot be converted to T#1    where 
    T#1,T#2 are type-variables: 
        T#1 extends Comparable<T#1> declared in class Edge 
        T#2 extends Object declared in interface Comparable
1 error

Shouldn't (this.weight) return a type 'T' instead of Comparable ? Also weight() method returns Comparable.

I do not understand this completely. It'll be great if someone can clarify why am I receiving this error. The error goes away on replacing this.weight with this.weight().

public class Edge<T extends Comparable<T>> implements Comparable<Edge>{
    private int vertex1;
    private int vertex2;
    private T weight;

    public Edge(int vertex1, int vertex2, T weight){
        this.vertex1 = vertex1;
        this.vertex2 = vertex2;
        this.weight = weight;
    }

    public int either(){
        return vertex1;
    }

    public int from(){
        return vertex1;
    }

    public int other(){
        return vertex2;
    }

    public int to(){
        return vertex2;
    }

    public Comparable weight(){
        return weight;
    }

    public String toString(){
        String s = "";
        s += vertex1 + " " + vertex2 + " " + weight;
        return s;
    }

    @Override
    public int compareTo(Edge e){
        return (this.weight).compareTo(e.weight());
    }

}
takendarkk
  • 3,347
  • 8
  • 25
  • 37
truth_seeker
  • 345
  • 4
  • 14

1 Answers1

3

Your class Edge has a type parameter, but you are using the raw type Edge without a type parameter. Add the type parameter:

public class Edge<T extends Comparable<T>> implements Comparable<Edge<T>> {
    // ...

    @Override
    public int compareTo(Edge<T> e) {
        return this.weight.compareTo(e.weight);
    }
}

Also, why does the method weight() return a Comparable? It should return T instead.

public T weight() {
    return weight;
}
Community
  • 1
  • 1
Jesper
  • 202,709
  • 46
  • 318
  • 350
  • Thank you. I made the suggested changes but I still receive the error on using weight on one instance and weight() method on the other like this -> return (this.weight).compareTo(e.weight()); Any idea why do I receive the error - (Comparable cannot be converted to the T) ? – truth_seeker Jul 04 '16 at 15:09
  • @DeeptiSabnani because your method `weight()` returns `Comparable` instead of `T`, as I also mentioned in my answer above. – Jesper Jul 04 '16 at 20:46