PDA

Click to See Complete Forum and Search --> : Collections.sort() and Generics?


<ABX
Nov 11th, 2006, 07:04 PM
I'm getting a warning when calling collections.sort() when passing an ArrayList
containing instances of subclasses of an abstract class.



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




public class Drunk extends Person {

public double BAC = 0;

public Drunk() {
super();
}

} // Drunk





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.

CornedBee
Nov 11th, 2006, 07:17 PM
Person shouldn't be generic in the first place. It should just be
class Person implements Comparable<Person>
...
public int compareTo(Person o)
...

Then see if the problem persists.

<ABX
Nov 11th, 2006, 07:24 PM
Hrm... that makes much more sense. It seems I need to re-read a chapter or two :P