Can someone explain why the following doesn’t work? It complains that:
The method add(C) in the type List is not applicable for the arguments (Generics.Person)
import java.util.ArrayList;
import java.util.List;
public class Generics<C extends Comparable<C>> {
static class Person implements Comparable<Person> {
public final String name, city;
public Person(String name, String city) {
this.name = name;
this.city = city;
}
@Override
public int compareTo(Person that) {
return 0;
}
}
public Generics() {
List<C> persons = new ArrayList<C>();
persons.add(new Person(null, null));
}
// however, this one works, but it gives a warning
// about Comparable being a raw type
public Generics() {
List<Comparable> persons = new ArrayList<Comparable>();
persons.add(new Person(null, null));
}
}
So, basically, what I want is a generic List of Comparables, to which I can add any type that implements Comparable.
To be allowed to do what you need to do you should specify the type parameter of the
Genericsclass from outside:Otherwise you are just adding a
Personto a list which has an unbound type variable, this is not allowed. While using theGenericsclass with a free type variable you must not make any assumption on the type of C.To see a clear example think about having a second
class Place extends Comparable<Place>. According to what you are trying to do you should be allowed to do the following:since also
Placeis a valid candidate. Then which would be the type of type variableC? Mind that there is no unification process that tries to guess the right type ofCaccording to what you are adding to the list, and finally you should seeCnot as a “whatever type as long as it fulfills the constraints” but as a “specified type that fulfills the constraints”,