JAVA 泛型中的通配符 (T,E,K,V,?)的使用及区别示例
package com.inspur.iaisnacos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class Generics<T> {
public static void main(String[] args) {
}
private void specifyType(){
GenericsTest1<String> genericsTest1 = new GenericsTest1<>();
genericsTest1.set("test");
String s = genericsTest1.get();
System.out.println(s);
}
private void noSpecifyType(){
GenericsTest1 genericsTest1 = new GenericsTest1<>();
genericsTest1.set("test");
Object o = genericsTest1.get();
System.out.println(String.valueOf(o));
}
}
class GenericsTest1<T> {
private T value;
protected T get( ){
return value;
}
protected void set(T key){
this.value = key;
}
}
class GenericsTest2{
private void get1(List<? extends Map> key){
return;
}
protected<T extends Map> void get2(List<T> key){
return ;
}
public <T extends Map> void get3(List<T> dest, List<T> src){
}
public void get4(List<? extends Map> dest, List<? extends Number> src){
}
public <T extends String & Map> void get5(List<T> dest, List<T> src){
}
public void get6(List<? super Map> key){
}
}
class GenericsTest3{
public static <T> T getClass(Class<T> className) throws IllegalAccessException, InstantiationException {
return className.newInstance();
}
public static void main(String[] args) throws InstantiationException, IllegalAccessException {
GenericsTest1 aClass = getClass(GenericsTest1.class);
}
public Class<?> clazz;
}
参照资料:
聊一聊-JAVA 泛型中的通配符 T,E,K,V,?
|