[英]Method returning a List<T> with parameters List<S1>, List<S2>, where S1 and S2 extends T
I have this method: 我有这个方法:
public static <T> List<T> flat(List<T>... lists){
return Stream.of(lists)
.filter(Objects::nonNull)
.flatMap(List::stream)
.collect(toList());
}
The idea is to flat a list of lists and return a list with the same type. 我们的想法是平放列表列表并返回相同类型的列表。
Suppose that A
and B
extends C
. 假设
A
和B
扩展C
This does not work: 这不起作用:
List<A> listOfA;
List<B> listOfB;
List<C> listOfC = flat(listOfA, listOfB);
Because List<A>
is not a List<C>
! 因为
List<A>
不是List<C>
!
Anyone know how to write a flat method signature with generics that admits what I'm trying to do? 任何人都知道如何使用泛型来编写平面方法签名,承认我正在尝试做什么?
Thanks! 谢谢!
If A
extends C
, B
extends C
, then List<A>
and List<B>
are assignable to List<? extends C>
如果
A
扩展C
, B
扩展C
,则List<A>
和List<B>
可分配给List<? extends C>
List<? extends C>
. List<? extends C>
。
So you can declare it this way: 所以你可以这样声明:
public static <T> List<T> flat(List<? extends T>... lists)
Test: 测试:
public static void main(String[] args) {
List<String> listOfString = List.of("sss"); // String extends from Object
List<Integer> listOfInt = List.of(1); // Integer extends from Object
List<Object> list = flat(listOfString, listOfInt);
System.out.println(list); // [sss, 1]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.