I am new to wildcards and am having an issue iterating through a Collection type. I had to transform this function to work on any Collection type, not just List and here is what I did:
void sell(List<T> items) {
for (T e : items) {
stock.add(e);
}
}
changed to:
void sell(Collection<? super T> items) {
Iterator ir = items.iterator();
while (ir.hasNext()){
stock.add((T)ir.next());
}
}
However, when I compile the code I receive the errors:
Note: Shop.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
Am I not using iterable correctly? Any help is appreciated!
First of all, since you are fetching items from the collection, you should use ? extends T
instead of ? super T
.
Secondly, you should use parameterized Iterator
, and not raw type. That is why you are getting that warning.
Change your method to:
void sell(Collection<? extends T> items) {
Iterator<? extends T> ir = items.iterator();
while (ir.hasNext()){
stock.add(ir.next());
}
}
You can still use the original for
loop with Collection<? extends T>
.
The problem is that you don't define T in the class. So you have to add parameterized type to this class. Here is the modified class line:
public class YourClassName<T> // add <T> as parameterized type
I purpose this will work for you at all. Get more information of generic type, just take a look at Generic Type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With