java - Comparable cannot be converted to T#1 -


i have piece of code takes generic of type comparable , class implements comparable interface. receive error on compareto() method in class stating comparable cannot converted t#1.

the complete error message is->

edge.java:40: error: method compareto in interface comparable<t#2> cannot applied given types;         return (this.weight).compareto(e.weight());                         ^     required:          t#1 found: comparable reason: argument mismatch; comparable cannot converted t#1         t#1,t#2 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 type 't' instead of comparable ? weight() method returns comparable.

i not understand completely. it'll great if can clarify why receiving error. error goes away on replacing this.weight 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());     }  } 

your class edge has type parameter, using raw type edge without type parameter. add 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 method weight() return comparable? should return t instead.

public t weight() {     return weight; } 

Comments

Popular posts from this blog

java - Static nested class instance -

c# - Bluetooth LE CanUpdate Characteristic property -

JavaScript - Replace variable from string in all occurrences -