Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast List<? extends Foo> to List<Foo>

Spring Batch's ItemWriter interface is this:

write(List<? extends T> items); 

I'd like the ItemWriter to call a Service but my service has this:

process(List<T> items); 

AFAIK, Java Generics are strict about casting types within collections.

like image 875
pri Avatar asked Oct 14 '11 20:10

pri


2 Answers

List<? extends Foo> list1 = ...
List<Foo> list2 = Collections.unmodifiableList(list1);

Reason why list2 has to be read-only view of list1 is nicely explained in an answer of Generics : List is same as List?

like image 140
czerny Avatar answered Sep 28 '22 15:09

czerny


Just go ahead and cast it. For reading, List<? extends Foo> is certainly a List<Foo>, the cast is absolutely safe. You can wrap it with Collections.unmodifiableList() if you are paranoid.

List<? extends Foo> foos1 = ...;

@SuppressWarnings("unchecked")
List<Foo> foos2 = (List<Foo>)(List<?>)foos1;    
like image 40
irreputable Avatar answered Sep 28 '22 17:09

irreputable