I am playing with generics in Java. But I do have currently problem. In short this code should be converting one object of one list and than putting it in another list. (From T to U)
My code looks like that
public class ListConvertor<T, U> {
private final Convertor<T, ? extends U> convertor;
public ListConvertor( Convertor<T, ? extends U> convertor ) {
this.convertor = convertor;
}
public void convertList( List<T> from, List<U> to ) {
if ( from == null )
return;
for ( T ch : from ) {
to.add( convertor.convert( ch ) );
}
}
}
public interface Convertor<T, V> {
V convert( T dataModelObject ) throws JEDXException;
}
It is working correctly for something like this:
new ListConvertor<>(new IntListConvertor()).convertList(in.getIntLists(), out.getIntLists());
When using this code like above everything is working correctly, because int
and out
getIntList
methods are returning List<IntList>
and List<IntListType>
public final class IntListConvertor implements Convertor<IntList, IntListType>
But I would like to use it aswell with List<Object>
on out parameter. So it would looks like that:
List<Object> outObjectList = new ArrayList<Object>();
new ListConvertor<>(new IntListConvertor()).convertList(in.getIntLists(), outObjectList );
But when using that like this I am getting error:
The method convertList(List<IntCharacteristic>, List<IntCharacteristicType>) in the type ListConvertor<IntCharacteristic,IntCharacteristicType> is not applicable for the arguments (List<IntCharacteristic>, List<Object>)
You should change the method signature from
public void convertList(List<T> from, List<U> to)
to
public void convertList(List<T> from, List<? super U> to)
If U
is Integer
you can now accept the following to lists
List<Integer>
List<Number>
List<Object>
Further tipps
You should also change List<T> from
to List<? extends T> from
. This way if T is Number
you can pass
List<Number>
List<Integer>
List<Double>
- ...