public class Test {
public List list = new ArrayList();
public static void main(String[] args) {
Test test = new Test();
test.list.add("hello");
System.out.println(test.list);
}}
public interface Mymap {
public K getKey();
public V getValue();
}
public class MymapImpl implements Mymap {
private K key;
private V value;
public MymapImpl(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() { return key; }
public V getValue() { return value; }
}
下来就可以传入任意类型,创建实例了,不用转化类型
Mymap mp1= new MymapImpl("Even", 8);
Mymap mp2= new MymapImpl("hello", "world");
Mymap mp3= new MymapImpl(888, 888);
如果要定义超过两个,三个或三个以上的泛型参数可以使用T1, T2, ..., Tn,像这样子
public class Test {
public void print(T1 t1,T2 t2,T3 t3){
System.out.println(t1.getClass());
System.out.println(t2.getClass());
System.out.println(t3.getClass());
}
}
public class Test {
public static T createInstance(Class clazz) throws IllegalAccessException, InstantiationException {
return clazz.newInstance();
}
public static void main(String[] args) throws IllegalAccessException, InstantiationException {
Fruit fruit= createInstance(Fruit .class);
People people= createInstance(People.class);
}
}