简体   繁体   English

返回List的方法 <T> 带参数列表 <S1> ,列表 <S2> ,其中S1和S2延伸T.

[英]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 . 假设AB扩展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扩展CB扩展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.

相关问题 改进我的Java方法containsSubstring(s1,s2),它查找s2是否为s1的子字符串 - Improving my Java method containsSubstring(s1, s2) which finds if s2 is a substring of s1 S1包含带有正则表达式的s2 - S1 contains s2 with regex 为什么选择System.out.println(“嘿s1 == s2:”+ s1 == s2); 打印“false”作为输出而不是打印“hey s1 == s2:false” - Why System.out.println(“hey s1==s2:”+s1==s2); prints “false” as the output instead of printing “hey s1==s2:false” String s1 == String s2(true)但FieldOffset不同 - String s1 == String s2 (true) but FieldOffset is different 如何更改Student类,以便当s1 = new Student()和s2 = new Student()时,s1 == s2返回true? - How to change Student class so that s1 == s2 return true when s1 = new Student() and s2 = new Student()? String s = s1 + s2;(s1和s2是字符串文字)从何处返回? 堆或池 - Where does String s= s1+s2;(s1 & s2 are String literals) returns from? heap or pool 为什么哈希码对于String s1 =“cat”和String s2 = new String(“cat”)是相同的? - Why hash code is same for String s1= “cat” and String s2= new String(“cat”)? 我究竟做错了什么。 将 s1 的值复制到元素 von s2 - What am i doing wrong. copy the the values of s1 into the element von s2 应该使用java将S1的每个备用索引中的字符替换为S2 - Character in each alternate index of S1 should be replaced with S2 using java 使用可比较或比较器接口使用String s1的顺序对String s2进行排序 - Sort String s2 using the order of String s1 using either of comparable or comparator interface
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM