gpt4 book ai didi

java - 实际参数 List<>> 无法通过方法调用转换转换为 List>

转载 作者:行者123 更新时间:2023-11-29 07:47:59 28 4
gpt4 key购买 nike

我做了一个静态类方法(这里称为“函数”)f需要一个列表 Callable<String>小号:

import java.util.concurrent.*;
import java.util.*;
class A {
static void f(List<Callable<String>> l) {}
static <T> List<T> s(T t) {
LinkedList<T> l = new LinkedList<T>();
l.add(t);
return l;
}
public static void main(String[] _) {
f(s(new Callable<String>() {
public String call() throws Exception {
return "HI";
}
}));
}
}

我做了另一个函数 s将单个元素包装在列表中,因此我可以用单个 Callable 制作一个列表在里面测试f .

除非我提取 Callable,否则编译失败成一个变量。为什么?

在 eclipse 中,它得到这个错误:

The method f(List<Callable<String>>) in the type A is not applicable for the arguments (List<new Callable<String>(){}>)

这很奇怪。似乎在说一个表达式(产生一个值)是一种类型。使用 javac 它会得到一个不同的错误:

A.java:11: error: method f in class A cannot be applied to given types;
f(s(new Callable<String>() {
^
required: List<Callable<String>>
found: List<<anonymous Callable<String>>>
reason: actual argument List<<anonymous Callable<String>>> cannot be converted to List<Callable<String>> by method invocation conversion
1 error

最佳答案

更改f的签名上限为 Callable .

static void f(List<? extends Callable<String>> l) {}

这是必需的,因为:

  1. 匿名类实际上是已声明接口(interface)/父类(super class)的子类
  2. 一个List<subclass> 不可分配给List<superclass>

关于java - 实际参数 List<<anonymous Callable<String>>> 无法通过方法调用转换转换为 List<Callable<String>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23797579/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com