Can anyone help me I am getting an error when I run this pro
Can anyone help me I am getting an error when I run this program and I can\'t figure out why, and help would be great.
The error is
./Shop.java:19: error: incompatible types: CAP#1 cannot be converted to T
for (T e : items)
^
where T is a type-variable:
T extends Object declared in class Shop
where CAP#1 is a fresh type-variable:
CAP#1 extends Object super: T from capture of ? super T
My program is located below
import java.util.*;
public class Shop<T>
{
List<T> stock;
public Shop() { stock = new java.util.LinkedList<T>(); }
void sell(T item)
{
stock.add(item);
}
public T buy()
{
return stock.remove(0);
}
void sell(Collection<? super T> items)
{
for (T e : items)
{
stock.add(e);
}
}
void buy(int n, Collection<? super T> items)
{
for (T e : stock.subList(0, n))
{
items.add(e);
}
for (int i=0; i<n; ++i) stock.remove(0);
}
}
public static void main(String[] args)
{
Shop<String> shop = new Shop<String>();
List<String> Shoppinglist = new LinkedList<String>();
Slist.add(\"Toy\");
Slist.add(\"Food\");
Slist.add(\"Cloths\");
shop.sell(Slist);
List<String> Buyinglist = new LinkedList<String>();
shop.buy(1,Buyinglist);
System.out.println(Buyinglist);
}
}
Solution
import java.util.*;
public class Shop<T>
{
List<T> stock;
public Shop() { stock = new java.util.LinkedList<T>(); }
void sell(T item)
{
stock.add(item);
}
public T buy()
{
return stock.remove(0);
}
void sell(Collection<? extends T> items) // changes super to extends
{
for (T e : items)
{
stock.add(e);
}
}
void buy(int n, Collection<? super T> items)
{
for (T e : stock.subList(0, n))
{
items.add(e);
}
for (int i=0; i<n; ++i)
stock.remove(0);
}
// adding the main function inside the class
public static void main(String[] args)
{
Shop<String> shop = new Shop<String>();
List<String> Shoppinglist = new LinkedList<String>();
Shoppinglist.add(\"Toy\");
Shoppinglist.add(\"Food\");
Shoppinglist.add(\"Cloths\");
shop.sell(Shoppinglist);
List<String> Buyinglist = new LinkedList<String>();
shop.buy(1,Buyinglist);
System.out.println(Buyinglist);
}
}
------------------output-------------------
[Toy]
-----------------output ends-----------------
note: changes asked is mentioned in the comments. Feel free to ask questions. God bless you!


