我注意到泛型类的原始类型可以采用(指向)泛型类的所有不同变体,并且泛型类的所有不同变体都可以采用(指向)泛型类的原始类型。为什么 Java 泛型会有这样的行为?纯粹是因为兼容旧版本的Java吗?
例子:
//Main.java
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
List listRaw = new ArrayList();
List<Student> listQualified = new ArrayList<Student>();
List<?> listUnbounded = new ArrayList<Student>();
List<? extends Student> listUpBounded = new ArrayList<Student>();
List<? super Student> listDownBounded = new ArrayList<Student>();
// List raw type can take all different variations of List
List rawList1 = listRaw;
List rawList2 = listQualified;
List rawList3 = listUnbounded;
List rawList4 = listUpBounded;
List rawList5 = listDownBounded;
// All different variations of List can take List raw type
listRaw = rawList1;
listQualified = rawList2;
listUnbounded = rawList3;
listUpBounded = rawList4;
listDownBounded = rawList5;
}
}
//People.java
public class People {
public static class Student extends People {
}
public class HistoryStudent extends Student {
}
public class MathStudent extends Student {
}
}