Java泛型作为方法的参数

Java泛型作为方法的参数,java,generics,Java,Generics,我有一个关于Java中泛型的问题,我似乎找不到答案。这是我目前的代码: 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;

我有一个关于Java中泛型的问题,我似乎找不到答案。这是我目前的代码:

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;
    }
}
因此,基本上,我必须定义这个类BooksByPrice,它实现接口ISelect,并充当谓词,在另一个类接口中用作列表实现的过滤器方法中使用。BooksByPrice应该选择这个方法,如果一本书的价格介于低和高之间,这个方法返回true。BooksByPrice类的整个主体可能会发生更改,但接口必须保持其在代码中的状态。是否有某种方法可以实例化BooksByPrice类中的泛型类型T,以便它可以使用book的方法和字段?否则,我看不出select方法将泛型作为参数的原因

谢谢您的帮助。

您需要给T一个上限:

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

    ...

    public boolean select(T book) {
        return book.getPrice() >= this.low && book.getPrice() <= this.high;
    }
}
使用哪种方法是一种设计决策,取决于BookByPrice是否需要对不同的图书子类通用。

您需要给T一个上限:

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

    ...

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

使用哪种方法是一种设计决策,这取决于BookByPrice是否需要对书籍的不同子类通用。

在本例中,实际上不需要BookByPrice的通用参数。您只需将其声明为类BookByPrice实现ISelect。在本例中,您实际上不需要BookByPrice上的泛型参数。您只需将其声明为BookByPrice实现ISelect的类。两种解决方案中的任何一种都比另一种更合适吗?非常感谢您的回复,顺便说一句,问题解决了。请参阅我最近的编辑-如果您需要任何澄清,请告诉我。非常好,我感谢您的全面回答。两种解决方案中的任何一种都比另一种更合适吗?非常感谢您的回复,顺便说一句,问题解决了。请参阅我最近的编辑-如果您需要任何澄清,请告诉我。非常好,我感谢您的全面回答。