public class _01_TestGeneric {
public static void main(String[] args) {
// TODO Auto-generated method stub
// MyCollection myCollection = new MyCollection();
// 让程序更加稳定
MyCollection<String> myCollection = new MyCollection<String>();
myCollection.set("Except", 0);
myCollection.set("Shout", 3);
// Integer integer = (Integer)myCollection.get(0); // 类型检查,返回String类型,无法强转
String string = (String)myCollection.get(3);
}
}
class MyCollection<E>{ // <E>代表后期传入参数的类型
Object[] object = new Object[5];
public void set(/*Object*/E object1,int index) {
object[index] = object1;
}
public /*Object*/E get(int index) {
return (E)object[index];
}
}