我对 ArrayList 和泛型有点困惑,例如,在下面的程序中,当我声明 Gen<Integer>iOb=new Gen<Integer>(88);
时它声明了 Integer 的泛型类型正确吗?但是,如果我以同样的方式声明一个数组列表呢?对于数组列表,它是尖括号中的类型,但是,研究泛型时,它说尖括号中的类型是泛型类型?我如何知道它是类类型的数组列表还是泛型?
//A simple generic class
//Here, T is a type parameter that
///will be replaced by a real type
//when an object of type gen is created
class Gen<T> {
T ob;//declare an object of type T
//Pass the constructor a refernce to
//an object of type T
Gen(T o) {
ob = o;
}
//return ob
T getob() {
return ob;
}
//show type of t
void showType() {
System.out.println("Type of T is " + ob.getClass().getName());
}
}
class GenDemo {
public static void main(String[] args) {
//create a gen reference for integers
Gen<Integer> iOb;
//Create a Gen<Integer>Object and assign its
//reference to iob, notice the use of autoboxing
//to encapsulate the value 88 within an integer object
iOb = new Gen<Integer>(88);
//show the type off data used by iob
iOb.showType();
//get the value in Iob notice that no cast is needed
int v = iOb.getob();
System.out.println("Value: " + v);
System.out.println();
//create a gen object for strings
Gen<String> strOb = new Gen<String>("Generic Test");
//show the type of data
strOb.showType();
//get the value of strOb, again notice that no cast is needed
String str = strOb.getob();
System.out.println("Value :" + str);
}
}
最佳答案
您似乎混淆了泛型类型和类型参数的概念。
鉴于您的类(class):
class Gen<T> {
// ...
}
Gen
是一个泛型类(一种特定类型的泛型类型),因为它被声明为至少有一个类型参数,在本例中 T
。当您实例化Gen
时,有时在其他情况下,您提供绑定(bind)到 T
的类型表达式:
Gen<?> gen = new Gen<String>();
给定的类型表达式( ?
和 String
)通常也称为“类型参数”,就像 T
一样。上课Gen
的定义。特定类型参数可以由泛型类构成(例如: List<String>
中的 Gen<List<String>>
),但“泛型类”不是“类型参数”的同义词。
ArrayList
是一样的。它是一个具有一个类型参数的泛型类。特定声明提供类型表达式来充当这些类型参数的值:
List<Integer> list = new ArrayList<Integer>();
那里,List<E>
和ArrayList<E>
是泛型类型;后者是一个特殊的泛型类。 Integer
两侧是适用于 list
声明的类型参数以及 ArrayList
的实例化;在这种情况下或任何其他情况下,它不被称为“通用类”。
关于java - 泛型与泛型数组列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38085114/