答案其实很简单,都是非常基础的东西,但是平时可能不太在意这些细节,在找的时候也有可能不太确定(对我来说 :))。
答案如下:
答案如下:
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.junit.Test;
public class GenericTest {
static class Person {
public void m(Collection<Person> persons) {
}
}
//泛型声明要放在返回值的前面,所以<T>要放在void前面
static class Employee extends Person {
public void <T> isManager() {
}
}
//泛型不具有协变性,所以下面是编译不了的
static class Student extends Person {
public void m2(Collection<Student> students) {
super.m(students);
}
}
//数组具有协变性,对于用父类声明的子类数组,在设置其他子类对象的时候虽然编译不报错,但是运行时会抛出ArrayStoreException
@Test(expected=ArrayStoreException.class)
public void arrayStoreExceptionTest() {
Person[] persons = new Employee[5];
persons[0] = new Employee();
persons[1] = new Student();
}
//下面是正确的
@Test
public void arrayStoreTest() {
Person[] persons = new Person[2];
persons[0] = new Employee();
persons[1] = new Student();
}
//下面语句在编译时就会出错,体现出泛型列表不具有协变性
public void genericTest() {
List<Person> personList = new ArrayList<Employee>();
}
//static方法和static域均不可引用类的泛型变量,下例中即T
static class Generic<T> {
static T t;
static void method1(T t) {
}
void m1(T t){
}
}
}