修改一下,“应该是不同类型参数的范型类都共有一个运行时类”比如ArrayList<String>和ArrayList<Integer>在运行时是看作同一个类的,然后需要时都是强制类型转换下面抄了一段原文: 7.1 A Generic Class is Shared by all its Invocations What does the following code fragment print? List <String> l1 = new ArrayList<String>(); List<Integer> l2 = new ArrayList<Integer>(); System.out.println(l1.getClass() == l2.getClass()); You might be tempted to say false, but you’d be wrong. It prints true, because all instances of a generic class have the same run-time class, regardless of their actual type parameters. Indeed, what makes a class generic is the fact that it has the same behavior for all of its possible type parameters; the same class can be viewed as having many different types. As consequence, the static variables and methods of a class are also shared among all the instances. That is why it is illegal to refer to the type parameters of a type declaration in a static method or initializer, or in the declaration or initializer of a static variable.
7.1 A Generic Class is Shared by all its Invocations
What does the following code fragment print?
List <String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass());
You might be tempted to say false, but you’d be wrong. It prints true, because all
instances of a generic class have the same run-time class, regardless of their actual type
parameters.
Indeed, what makes a class generic is the fact that it has the same behavior for all
of its possible type parameters; the same class can be viewed as having many different
types.
As consequence, the static variables and methods of a class are also shared among
all the instances. That is why it is illegal to refer to the type parameters of a type
declaration in a static method or initializer, or in the declaration or initializer of a static
variable.