Transfering a set with a Wildcarded Generic to a List in Java
- by Daniel Bingham
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?