2

I have a question about generics in Java that I can't seem to find the answer to. Here is my current code:

interface ISelect<T>{
    // a predicate that determines the properties of the given item
    public boolean select(T t);
}

class BookByPrice<T> implements ISelect<T> {
    int high;
    int low;

    public BookByPrice(int high, int low) {
        this.high = high;
        this.low = low;
    }

    public boolean select(T t) {
        return t.getPrice() >= this.low && t.getPrice() <= this.high;
    }
}

So, basically, I have to define this class BooksByPrice that implements the interface ISelect and acts as a predicate to be used in a filter method in another interface of classes that acts as a list implementation. BooksByPrice is supposed to have this method select that returns true if a book's price is between low and high. The entire body of the BooksByPrice class is subject to change, but the interface must remain as it is in the code. Is there some way to instantiate the generic type T in the class BooksByPrice so that it can use the methods and fields of a book? Otherwise I see no reason that the select method has a generic as a parameter.

Thanks for any help.

1
  • 1
    In this example you don't actually need a generic parameter on BookByPrice. You can simply declare it as class BookByPrice implements ISelect<BookByPrice>. Commented Mar 7, 2013 at 5:38

1 Answer 1

4

You need to give T an upper bound:

class BookByPrice<T extends Book> implements ISelect<T> {

    ...

    public boolean select(T book) {
        return book.getPrice() >= this.low && book.getPrice() <= this.high;
    }
}

Or else implement ISelect with a concrete type argument:

class BookByPrice implements ISelect<Book> {

    ...

    public boolean select(Book book) {
        return book.getPrice() >= this.low && book.getPrice() <= this.high;
    }
}

Which approach to use is a design decision depending on whether BookByPrice needs to be generic to different subclasses of books.

Sign up to request clarification or add additional context in comments.

3 Comments

Is either solution more appropriate than the other? Thanks a lot for the response btw, problem solved.
See my most recent edit - let me know if you need anything clarified.
Excellent, I appreciate the thorough answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.