Transfering a set with a Wildcarded Generic to a List in Java

Posted by Daniel Bingham on Stack Overflow See other posts from Stack Overflow or by Daniel Bingham
Published on 2010-04-15T19:40:08Z Indexed on 2010/04/15 19:43 UTC
Read the original article Hit count: 210

Filed under:
|

I have a data type that contains a set and a method that expects List<? extends MyClass>. The data type has Set<? extends MyClass>. I need to be able to move the stuff out of the set and into the List. The order it goes into the list doesn't matter, it just needs to start keeping track of it so that it can be reordered when displayed. Suffice to say that changing the Set into a List in the data type is out of the question here.

This seems pretty easy at first. Create a new method that takes a Set instead of a List, changes it into a list and then passes it on to the old method that just took a list. The problem comes in changing the set to a list.

public void setData(Set<? extends MyClass> data) {
    List<? extends Myclass> newData = ArrayList< /* What goes here? */ >();
    for(ConcordaEntityBean o : data) {
        newData.add(o);
     }
     setData(newData);
}

Obviously, I can't instantiate an ArrayList with a wildcard, it chokes. I don't know the type at that point. Is there some way to pull the type out of data and pass it to ArrayList? Can I just instantiate it with MyClass? Is there some other way to do this?

© Stack Overflow or respective owner

Related posts about java

Related posts about generics