简体   繁体   English

Java泛型作为方法的参数

[英]Java generics as parameters to methods

I have a question about generics in Java that I can't seem to find the answer to. 我有一个关于Java泛型的问题,我似乎找不到答案。 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,该类实现接口ISelect并充当谓词,以在用作列表实现的类的另一个接口的过滤器方法中使用。 BooksByPrice is supposed to have this method select that returns true if a book's price is between low and high. 如果书籍的价格介于低价和高价之间,BooksByPrice应该选择此方法返回true。 The entire body of the BooksByPrice class is subject to change, but the interface must remain as it is in the code. BooksByPrice类的整个主体都可能会发生变化,但是该接口必须保留在代码中。 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? 有没有办法在类BooksByPrice中实例化通用类型T,以便它可以使用书籍的方法和字段? Otherwise I see no reason that the select method has a generic as a parameter. 否则,我认为没有理由将select方法具有泛型作为参数。

Thanks for any help. 谢谢你的帮助。

You need to give T an upper bound: 您需要给T一个上限:

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: 否则用一个具体的类型参数实现ISelect

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. 使用哪种方法是设计决策,具体取决于BookByPrice是否需要对书籍的不同子类通用。

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

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