I have an ArrayList of instances of a class I created, each of which contains a single field with a String. I have implemented Comparable in the class I created. How do I sort the Array List?
+7
A:
edit
No errors for me
class Gene {
}
class MyGene extends Gene implements Comparable<MyGene> {
public int compareTo(MyGene o) {
throw new UnsupportedOperationException("Method is not implemented yet.");
}
}
...
List<MyGene> l = new ArrayList<MyGene>();
Collections.sort(l);
Nikita Rybak
2010-09-24 01:23:35
That seems like it ought to work, except Eclipse complains that, "the inferred type [myClass] is not a valid substitute for the bounded parameter<T extends comparable<? super T>>"
Trevor
2010-09-24 01:35:01
@Trevor You should define class like _class MyClass implements Comparable<MyClass>_ It will tell compiler that MyClass can be compared only with other MyClass instances.
Nikita Rybak
2010-09-24 01:42:29
I do have MyClass implementing MyClass in that way currently.
Trevor
2010-09-24 01:43:55
@Trevor Can you post its declaration, then?
Nikita Rybak
2010-09-24 01:47:00
public final class MyGene extends Gene implements Comparable<Gene> {
Trevor
2010-09-24 01:54:02
@Trevor try _Comparable<MyGene>_
Nikita Rybak
2010-09-24 01:57:50
The same complaint from Eclipse comes up when I change it to MyGene.
Trevor
2010-09-24 02:01:22