简体   繁体   English

泛型-如何返回T的图?

[英]Generics - how to return a Map of T?

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");

However, the return value ConcurrentSkipListMap<String, <T extends MyObject>> gives compilation error, but <T extends MyObject>T is ok. 但是,返回值ConcurrentSkipListMap<String, <T extends MyObject>>会给出编译错误,但是<T extends MyObject>T可以。 What should I write instead? 我应该写些什么呢?

Make these changes 进行这些更改

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");
}

I declared <T extends MyObject> before the return type and also added a variable x to hold the return value of the get function. 我在返回类型之前声明了<T extends MyObject> ,还添加了一个变量x来保存get函数的返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM