java - 错误参数 : why is a List<List<>> not equivalent to a List<Object>?

标签 java

<分区>

下面的代码给我一个编译错误:

public static Function<int[], Stream<Tuple2<Formatter, List<Object>>>> acquisitionColors = (col) -> Seq.of(
            Tuple.tuple(Formatter.COLOR,
                    Seq.of(
                            Seq.of(col).toList(),
                            Seq.of(
                                    Seq.of("Stop", "Stoq", null, "red").toList(),
                                    Seq.of("Learning", "Learninh", null, "gray").toList(),
                                    Seq.of("Stop", "Stoq", null, "red").toList(),
                                    Seq.of("Reduce", "Reducf", null, "orange").toList(),
                                    Seq.of("Keep", "Keeq", null, "green").toList(),
                                    Seq.of("Increase", "Increasf", null, "blue").toList()
                            ).toList()
                    ).toList()
            )
    );
Wrong 2nd argument type. Found: 'java.util.List<java.util.List<? extends java.lang.Object>>', required: 'java.util.List<java.lang.Object>' 
Inspection info:  
tuple (Formatter,java.uti.List<java.lang.Object>) in Tuple cannot be applied 
to (Formatter,java.util.List<java.util.List<? extends java.lanq.Object>>)

但是,如果我用 Collections.singletonList 包装该列表,它会起作用:

public static Function<int[], Stream<Tuple2<Formatter, List<Object>>>> acquisitionColors = (col) -> Seq.of(
            Tuple.tuple(Formatter.COLOR,
                    Collections.singletonList(
                     ...
                    ).toList())
            )
    );

为什么会这样?

最佳答案

答案的两个部分: List<Object>是不变的,因此表达式类型为 List<List<? extends java.lanq.Object>>不能分配给 List<Object> Google for variance in Java,例如: DZone article on variance in Java

public static <T> List<T> singletonList(T o)是一种通用方法。对于泛型方法,应用类型推断。在您的上下文中,T 应该是一个对象,并且 List<List<? extends java.lanq.Object>>可以转换为对象。 参见 What is type argument inference

关于java - 错误参数 : why is a List<List<>> not equivalent to a List<Object>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57877024/

相关文章:

java - 通过 Android 从 ble 设备发送和接收数据

java - 如何在 java 中在 int 输入之前获取 char 输入?

java加速图形

java - Spring 安全 : all endpoints return status 200 and unresponsive to constraints as antMatchers

java - 如何读取 Excel 日期并将其存储到我的数据库中?

java - 带有 String[] args 的 Eclipse 命令行参数

java - 如何使用java创建.doc文件?

java - 我的项目将部署在没有中间件的服务器上。这是什么意思?

Java Spark 按故障分组

java - 我该如何修复此方法