Java泛型不适用于参数List <Object>

Suu*_*ule 1 java java-8

我正在玩Java中的泛型。但是我确实有问题。简而言之,这段代码应该转换一个列表中的一个对象,而不是将其放入另一个列表中。(从T到U)

我的代码看起来像这样

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;

}
Run Code Online (Sandbox Code Playgroud)

对于以下内容,它可以正常工作:

new ListConvertor<>(new IntListConvertor()).convertList(in.getIntLists(), out.getIntLists());
Run Code Online (Sandbox Code Playgroud)

当像上面那样使用此代码时,一切正常,因为intand out getIntList方法正在返回,List<IntList>并且List<IntListType>

public final class IntListConvertor implements Convertor<IntList, IntListType>
Run Code Online (Sandbox Code Playgroud)

但我也想在List<Object>on out参数中使用它。所以看起来像这样:

List<Object> outObjectList = new ArrayList<Object>();
new ListConvertor<>(new IntListConvertor()).convertList(in.getIntLists(), outObjectList );
Run Code Online (Sandbox Code Playgroud)

但是当这样使用时,我得到了错误:

The method convertList(List<IntCharacteristic>, List<IntCharacteristicType>) in the type ListConvertor<IntCharacteristic,IntCharacteristicType> is not applicable for the arguments (List<IntCharacteristic>, List<Object>)
Run Code Online (Sandbox Code Playgroud)

小智 5

您应该将方法签名从

public void convertList(List<T> from, List<U> to)
Run Code Online (Sandbox Code Playgroud)

public void convertList(List<T> from, List<? super U> to)
Run Code Online (Sandbox Code Playgroud)

如果U是,Integer您现在可以接受以下列表

  • List<Integer>
  • List<Number>
  • List<Object>

进一步的小费

您还应该更改List<T> fromList<? extends T> from。这样如果T是Number你可以通过

  • List<Number>
  • List<Integer>
  • List<Double>
  • ...