我有点困惑ArrayLists和泛型,例如,在下面的程序中,当我声明,Gen<Integer>iOb=new Gen<Integer>(88);
它声明一个整数正确的通用类型?但是,如果我以同样的方式声明一个数组列表?在数组列表的情况下,它是尖括号中的类型,但是,研究泛型时,它说尖括号中的类型是泛型类型?我如何知道它是一个类类型或泛型的数组列表?泛型比较。数组列表?
//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”一样。什么让你感到困扰? – Tunaki
我知道在这段代码中没有arraylist,但是arraylist和generic是以同样的方式声明的,我怎么知道它是泛型还是Gen类型的ArrayList? – Eli
什么是你的“通用”?您是否阅读过https://docs.oracle.com/javase/tutorial/java/generics/? – Tunaki