Collections.sort() and Generics?
I'm getting a warning when calling collections.sort() when passing an ArrayList
containing instances of subclasses of an abstract class.
Code:
import java.lang.Comparable;
public abstract class Person<V extends Comparable> implements Comparable<V> {
public String name = "";
public int age = 0;
public Person() {
}
public int compareTo(V o) {
return this.age - o.age;
}
} // Person
Code:
public class Drunk extends Person {
public double BAC = 0;
public Drunk() {
super();
}
} // Drunk
Code:
import java.lang.Comparable;
import java.util.ArrayList;
import java.util.Collections;
public class GenericsTest {
public static void main(String[] args) {
ArrayList<Person> ppl = new ArrayList<Person>();
Drunk myDrunk1 = new Drunk();
Drunk myDrunk2 = new Drunk();
ppl.add(myDrunk1);
ppl.add(myDrunk2);
Collections.sort(ppl);
}
} // GenericsTest
Produces the warning: warning: [unchecked] unchecked method invocation: <T>sort(java.util.List<T>) in java.util.Collections is applied to (java.util.ArrayList<Person>)
Collections.sort(ppl);
^
I think there is something wrong with the way I'm declaring the abstract class Person.
Re: Collections.sort() and Generics?
Person shouldn't be generic in the first place. It should just be
Code:
class Person implements Comparable<Person>
...
public int compareTo(Person o)
...
Then see if the problem persists.
Re: Collections.sort() and Generics?
Hrm... that makes much more sense. It seems I need to re-read a chapter or two :P