[英]Java generics as parameters to methods
我有一个关于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,以便它可以使用书籍的方法和字段? 否则,我认为没有理由将select方法具有泛型作为参数。
谢谢你的帮助。
您需要给T
一个上限:
class BookByPrice<T extends Book> implements ISelect<T> {
...
public boolean select(T book) {
return book.getPrice() >= this.low && book.getPrice() <= this.high;
}
}
否则用一个具体的类型参数实现ISelect
:
class BookByPrice implements ISelect<Book> {
...
public boolean select(Book book) {
return book.getPrice() >= this.low && book.getPrice() <= this.high;
}
}
使用哪种方法是设计决策,具体取决于BookByPrice
是否需要对书籍的不同子类通用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.