【发布时间】:2016-06-28 19:50:20
【问题描述】:
我对 ArrayLists 和泛型有点困惑,例如,在下面的程序中,当我声明 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);
}
}
【问题讨论】:
-
这段代码中没有
ArrayList。 ArrayList 是一个类。一个通用类。就像Gen。究竟是什么让您感到困扰? -
我知道这段代码中没有arraylist,但是arraylist和generic的声明方式完全相同,我怎么知道它是generic还是Gen类型的ArrayList?跨度>
-
什么是“通用”?你读过docs.oracle.com/javase/tutorial/java/generics吗?
-
The tutorial 调用
Gen<T>泛型类型,T类型参数和Gen<Integer>参数化类型。 -
@jozencl,听起来,当您说“通用类型”时,您是在谈论其他人所说的 raw 类型。
ArrayList<T>是泛型类型,ArrayList是原始类型。您可以在代码中声明原始类型(例如,您可以声明一个引用ArrayList的变量,而无需说明ArrayList是什么,但如果这样做,您将不得不处理大量编译器警告。