泛型 - 如何返回T的地图?

时间:2018-05-19 04:06:44

标签: java generics

class MyObject{}
class Human extends MyObject{}

public ConcurrentSkipListMap<String, <T extends MyObject>> get(Class<T> clazz, Object... vars){
    //...
}

//use the get() with
ConcurrentSkipListMap<String, Human> mapOfAllAdams = get(Human.class, "Adam");

但是,返回值ConcurrentSkipListMap<String, <T extends MyObject>>会出现编译错误,但<T extends MyObject>T没问题。我该怎么写呢?

1 个答案:

答案 0 :(得分:1)

进行这些更改

class MyObject{}
class Human extends MyObject{}

public <T extends MyObject> ConcurrentSkipListMap<String, T> get(Class<T> clazz, Object... vars){
    //...

    return null;
}

//use the get() with
void hello(){
    ConcurrentSkipListMap<String, Human> x = get(Human.class, "Adam");
}

我在返回类型之前声明了<T extends MyObject>,并且还添加了一个变量x来保存get函数的返回值。