I'm trying to write a class, TelemeterTester, which implements the Telemeter class. Telemeter extends Comparator. I keep getting this runtime error...
TelemeterTester.java:12: error: cannot find symbol
return e1.compareTo(e2);
^
symbol: method compareTo(Comparable)
location: variable e1 of type Comparable
where Comparable is a type-variable:
Comparable extends Object declared in class TelemeterTester
1 error
Here is the code for Telemeter interface
/** @param <E> the type on which distance and order are defined
*
*/
public interface Telemeter<E> extends Comparator<E> {
/**
* Returns the distance between e1 and e2.
*
* @param e1 the first object
* @param e2 the second object
* @return the distance between e1 and e2
*
*/
double distance(E e1, E e2);
}
Here is my code for TelemeterTester class, which implements Telemeter
public class TelemeterTester<Comparable> implements Telemeter<Comparable>{
private TelemeterTester() {}
public double distance(Comparable e1, Comparable e2) {
return 0;
}
public int compare(Comparable e1, Comparable e2) {
return e1.compareTo(e2);
}
}
Can anyone explain to me what I'm doing wrong? I don't understand generics very well and I've been stuck on variations of this error for a few hours now.
Your TelemeterTester should be defined as below:
public class TelemeterTester<E extends Comparable<E>> implements Telemeter<E> {
private TelemeterTester() {
}
public int compare(E o1, E o2) {
return o1.compareTo(o2);
}
@Override
public double distance(E e1, E e2) {
return 0;
}
}
and referred as :
TelemeterTester<Integer> t = new TelemeterTester<Integer>();
System.out.println(t.compare(2, 2));
remember type Integer implements Comparable<Integer>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments