繁体   English   中英

构造泛型类

[英]Constructing a generic class

我有一个关于java泛型的简单问题。 我如何构建泛型类? 我有这门课:

public class SearchResult<T extends Model> {

    public List<T> results ;

    public Integer count ;

    public SearchResult(List<T> results, Integer count){
        this.results = results;
        this.count = count ;
    }
}

现在我想创建一个新的实例是SearchResult,但是当我这样做时,我得到一个错误。 SearchResult result = new SearchResult<MyModel>(myListOfMyModels, mycount);

现在我修改了格式,很明显发生了什么。 您声明泛型参数是扩展Model东西,但您尝试使用String参数值实例化该类。 我确信String不会扩展Model (不管是什么)。

T的类型需要限定为类或方法。

在这种情况下,您可能希望将类型参数T添加到搜索结果类中,如下所示:

public class SearchResult<T> {
    // as before
}

并将实例化更改为:

SearchResult<String> result = new SearchResult<String>(myListOfStrings, mycount);

编辑:最初SearchResult没有类型参数所以我建议添加一个。 如果问题是T必须扩展Model,那么您将无法创建SearchResult <String>,因为String不会扩展Model。

你的类定义应该是这样的

public class SearchResult<T> {

    public List<T> results ;

    public Integer count ;

    public SearchResult(List<T> results, Integer count){
        this.results = results;
        this.count = count ;
    }
}

然后:

SearchResult result = new SearchResult<String>(myListOfStrings, mycount);

我假设因为myListOfStrings似乎是一个字符串,所以你需要将T定义为String

暂无
暂无

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

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