Reputation: 343
I'v written a generic method to sort an object of Type T. My compiler is saying "cannot find symbol : method lte(T).
Any ideas what exactly my problem is?
interface Comparable<T>{
boolean lte(T t);
}
class Sort<T extends Comparable<T>> {
static <T> void sort(T[] s) {
for (int i = 0; i<s.length; i++) {
for (int j = i+1; j < s.length; j++) {
if (s[i].lte(s[j])) {
T t;
t = s[i];
s[i] = s[j];
s[j] = t;
}
}
}
}
public static void main(String[] args) {
String[] names = {"Pete","Jill","May","Anne","Tim"};
sort(names);
for (String s:names)
System.out.println(s);
}
}
Upvotes: 0
Views: 74
Reputation: 178263
You've made your sort
method generic, with another <T>
declaration, but it's not Comparable
. Your sort
method is static
, so it can't use the class's <T>
. In fact, the class's <T>
isn't used. Try this:
// Not generic here anymore
class Sort {
// Bound goes here
static <T extends Comparable<T>> void sort(T[] s) {
Additionally, String
doesn't extend your Comparable
interface, so this won't work (String
doesn't even have an lte
method, anyway). You will need to pass in some objects that implement your Comparable
.
At best, it's confusing to name your interface the same name as a built-in (and well-known) interface. I suggest renaming your Comparable
interface to something like Lteable
.
Upvotes: 1