使给定的Java类更通用和灵活

时间:2012-11-18 03:36:18

标签: java class wildcard subtype

我获得了一个类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

1 个答案:

答案 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的任何具体子类型进行实例化。

相关问题