Q:

Yet another Java generics question

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.

A:

To be allowed to do what you need to do you should specify the type parameter of the Generics class from outside:
Generics<Person> generic = new Generics<Person>();

Otherwise you are just adding a Person to a list which has an unbound type variable, this is not allowed. While using the Generics class 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:
public Generics() {
    List<C> persons = new ArrayList<C>();
    persons.add(new Person(null, null));
    persons.add(new Place());
  }

since also Place is a valid candidate. Then which would be the type of type variable C? Mind that there is no unification process that tries to guess the right type of C according to what you are adding to the list, and finally you should see C not as a "whatever type as long as it fulfills the constraints" but as a "specified type that fulfills the constraints",

