truth_seeker
truth_seeker

Reputation: 363

Comparable cannot be converted to T#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());
    }

}

Upvotes: 1

Views: 4732

Answers (1)

Jesper
Jesper

Reputation: 206796

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

Upvotes: 3

Related Questions