开发者

Constructing a generic class

I have a simple question regarding java generics. How do I c开发者_Python百科onstruct a generic class? I have this class :

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

Now i would like to create a new instance is SearchResult but then when i do this i get an error . SearchResult result = new SearchResult<MyModel>(myListOfMyModels, mycount);


Now that I fixed your formatting, it's clear what's happening. You declared the generic parameter to be something that extends Model, yet you're trying to instantiate the class with a String parameter value. I'm sure that String does not extend Model (whatever that is).


Your class definition should look like

public class SearchResult<T> {

    public List<T> results ;

    public Integer count ;

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

Then:

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

I'm assuming that since myListOfStrings appears to be a string, you need to define T as a String


The type of T needs to be scoped to something like a class or a method.

In this instance you probably want to add the type parameter T to the search result class, giving something like:

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

And change the instantiation to something like:

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

Edit: Initially SearchResult had no type parameter so I suggested adding one. If the issue is that T must extend Model, then you won't be able to create a SearchResult<String>, as String doesn't extend Model.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜