joshua
joshua

Reputation: 4198

Constructing a generic class

I have a simple question regarding java generics. How do I construct 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);

Upvotes: 0

Views: 152

Answers (3)

oconnor0
oconnor0

Reputation: 3234

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.

Upvotes: 0

Ted Hopp
Ted Hopp

Reputation: 234795

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).

Upvotes: 2

msarchet
msarchet

Reputation: 15232

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

Upvotes: 0

Related Questions