views:

76

answers:

1

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: 

Collections.sort

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
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
@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
I do have MyClass implementing MyClass in that way currently.
Trevor
@Trevor Can you post its declaration, then?
Nikita Rybak
public final class MyGene extends Gene implements Comparable<Gene> {
Trevor
@Trevor try _Comparable<MyGene>_
Nikita Rybak
The same complaint from Eclipse comes up when I change it to MyGene.
Trevor