? 表示不确定的java类型。
T 表示java类型。
K V 分别代表java键值中的Key Value。
E 代表Element。
Object跟这些东西代表的java类型有啥区别呢?
Object是所有类的根类,是具体的一个类,使用的时候可能是需要类型强制转换的,但是用T ?等这些的话,在实际用之前类型就已经确定了,不需要强制转换。
第一种是固定的一种泛型,第二种是只要是Object类的子类都可以,换言之,任何类都可以,因为Object是所有类的根基类
固定的泛型指类型是固定的,比如:Interge,String. 就是<T extends Collection>
<? extends Collection> 这里?代表一个未知的类型,
但是,这个未知的类型实际上是Collection的一个子类,Collection是这个通配符的上限.
举个例子
class Test <T extends Collection> { }
<T extends Collection>其中,限定了构造此类实例的时候T是一个确定类型(具体类型),这个类型实现了Collection接口,
但是实现 Collection接口的类很多很多,如果针对每一种都要写出具体的子类类型,那也太麻烦了,干脆还不如用
Object通用一下。
<? extends Collection>其中,?是一个未知类型,是一个通配符泛型,这个类型是实现Collection接口即可。
立即学习“Java免费学习笔记(深入)”;
The method take(Animal) in the type Test is not applicable for the arguments (Demo<Dog>) The method take(Animal) in the type Test is not applicable for the arguments (Demo<Cat>) The method take(Animal) in the type Test is not applicable for the arguments (Demo<Animal>)
public class Demo <T extends Animal>{ private T ob; public T getOb() { return ob;
} public void setOb(T ob) { this.ob = ob;
} public Demo(T ob) { super(); this.ob = ob;
}
public void print(){
System.out.println("T的类型是:"+ob.getClass().getName());
}
} public <T> Class<T> resolveAlias(String string) {
try {
if (string == null) {
return null;
}
// issue #748
String key = string.toLowerCase(Locale.ENGLISH);
Class<T> value;
if (TYPE_ALIASES.containsKey(key)) {
value = (Class<T>) TYPE_ALIASES.get(key);
} else {
value = (Class<T>) Resources.classForName(string);
}
return value;
} catch (ClassNotFoundException e) {
throw new TypeException("Could not resolve type alias '" + string + "'. Cause: " + e, e);
}
}public class Base {
private static Map<String, Class<?>> map = new HashMap<>();
static {
map.put("string", String.class);
map.put("integer", Integer.class);
}
@SuppressWarnings("unchecked")
public <T> Class<T> get(String str) {
return (Class<T>) map.get(str);
}
@Test
public void t() throws IllegalAccessException, InstantiationException {
Base base = new Base();
Class<Integer> string = base.get("string");
System.out.println(string);
}
}
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号