开发者

collections in java

So I have this code. Basically it should be able to take a stock of any type, and you should be able to buy from this stock into a collection of any type, including Objects.

For the main function i have this. Basically i have an stock inventory of strings, and I want to buy form this stock inventory of strings into a set of objects. However, I get this error.

add(capture#880 of ?) in java.util.Collection cannot be applied to (T)

import java.util.*;

public class lab6 {

    public static void main(String[] args) {
     Shop<String> turkey= new Shop<String>();
     turkey.sell("pork");
     turkey.sell("chicken");
     turkey.print();
     Set<Object> possessions= new HashSet<Object>();
     turkey.bu开发者_StackOverflow中文版y(2,possessions);
        for(String e:possessions)
      System.out.println(e);

    }
}

Then this is the class file.

 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, Collection<?> items) {

         for (T e : stock.subList(0, n)) {
            items.add(e);
        }
      for (int i=0; i<n; ++i) stock.remove(0);

    }
}


Replace your buy method with this:

void buy(int n, Collection<T> items) {

    for (T e : stock.subList(0, n)) {
        items.add(e);
    }
    for (int i=0; i<n; ++i) stock.remove(0);

}

You were using Collection<?>

EDIT:

Also change your main to this:

public static void main(final String[] args) {
    final Shop<String> turkey = new Shop<String>();
    turkey.sell("pork");
    turkey.sell("chicken");
    turkey.print();
    final Set<String> possessions = new HashSet<String>();
    turkey.buy(2, possessions);
    for (final String e : possessions) {
        System.out.println(e);
    }
}

and write a print() method in Shop.


The problem here is that Collection<?> can contain any type of object, and T may not be a subtype of the ? type. For example, you could pass in a Collection<Integer> and if T is String, clearly you can't do items.add(e).

You need to make sure that the Collection holds a supertype of T so that it is always valid to add a T, so try something like:

void buy(int n, Collection<? super T> items)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜