#源码
package cn.sxt.collection;
/*
* 测试泛型
* 作者:不忘初心
*
*/
/* 没有泛型的情况
public class TestGeneric {
public static void main(String[] Args) {
//
MyCollection mc =new MyCollection();
mc.set("xyz", 0);
mc.set(0000,1);
Integer a = (Integer) mc.get(0);
String b = (String) mc.get(0);
}
}
class MyCollection{
Object[] objs=new Object[5];
public void set(Object obj,int index) {
objs[index]=obj;
}
public Object get(int index) {
return objs[index];
}
}
*/
/*
* 使用泛型的情况
*/
public class TestGeneric {
public static void main(String[] Args) {
//
MyCollection <String> mc =new MyCollection <>(); //添加泛型
mc.set("xyz", 0);
// mc.set(0000,1);
// Integer a = (Integer) mc.get(0);
String b = (String) mc.get(0);
System.out.println(b);
}
}
class MyCollection <E>{ //利用泛型定义类
Object[] objs=new Object[5];
public void set(E e,int index) {
objs[index]=e;
}
public E get(int index) {
return (E) objs[index];
}
}
#执行结果