泛型演示
泛型可以指定某个特定的类,让使用这个类时,可以设定只传入某种类型的数据。
package cn.xxx.Collection; public class CollectionTest { public static void main(String[] args) { MyCollection<String> mc = new MyCollection<>();//泛型的声明,这里的<String>相当于实参 mc.set("hello", 0); String str = (String)mc.get(0); System.out.println(str); } } class MyCollection<E>{//这里的<E>相当于形参 Object[] objs = new Object[10]; public void set(E e,int index){ objs[index] = e; } public E get(int index){ return (E)objs[index]; } }