我获得了一个类Shop
,它维护了T
类型的项集合。它为单件或多件商品提供买卖功能,并使用List<T>
作为买卖的容器:
import java.util.*;
public class Shop<T> {
List<T> stock;
public Shop() { stock = new LinkedList<T>(); }
public T buy() {
return stock.remove(0);
}
void sell(T item) {
stock.add(item);
}
void buy(int n, List<T> items) {
for (T e : stock.subList(0, n)) {
items.add(e);
}
for (int i=0; i<n; ++i) stock.remove(0);
}
void sell(List<T> items) {
for (T e : items) {
stock.add(e);
}
}
}
现在,我需要修改此课程,以便我可以购买/销售任何Collection
类型的商品...而不仅仅是List
。我想我会首先评论大部分内容并尝试逐个转换,从stock
开始:
public class Shop<T> {
// List<T> stock;
Collection<T> stock;
// public Shop() { stock = new LinkedList<T>(); }
public Shop() { stock = new Collection<T>(); }
...
...
}
第一个声明有效,但尝试按照预期在构造函数中实例化接口不起作用。但据我所知,stock
需要Collection
,以便我可以在处理它的其他函数中使用任何Collection
子类型。而且我很确定在这种情况下我不能使用通配符作为类型参数。那么我究竟能在这里构建stock
...或者我应该如何首先声明stock
?
答案 0 :(得分:3)
只要您的接口定义接受Collection
,即您的类中的实际集合实现对于类的客户端/用户来说完全无关紧要,即
void buy(int n, List<T> items)
void sell(List<T> items)
应该是
void buy(int n, Collection<T> items)
void sell(Collection<T> items)
这不会限制任何人仅使用List
类型。然后,您的内部成员stock
可以并且应该使用Collection
的任何具体子类型进行实例化。