Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use iterable on Collection<? super T>

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!

like image 875
user2125844 Avatar asked Nov 20 '13 07:11

user2125844


Video Answer


2 Answers

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>.

like image 157
Rohit Jain Avatar answered Oct 08 '22 12:10

Rohit Jain


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.

like image 23
Engine Bai Avatar answered Oct 08 '22 12:10

Engine Bai