java - 泛型错误 : not applicable for the arguments

标签 java generics bounded-wildcard

有人可以向我解释一下为什么下面的代码不起作用吗?

public class Test {

 interface Strategy<T> {
   void execute(T t);
 }

 public static class DefaultStrategy<T> implements Strategy<T> {
   @Override
   public void execute(T t) {}
 }

 public static class Client {
   private Strategy<?> a;

   public void setStrategy(Strategy<?> a) {
     this.a = a;
   }

   private void run() {
     a.execute("hello world");
   }
 }

 public static void main(String[] args) {
   Client client = new Client();
   client.setStrategy(new DefaultStrategy<String>());
   client.run();
 }
}

我收到以下错误:

The method execute(capture#3-of ?) in the type Test.Strategy<capture#3-of ?> 
is not applicable for the arguments (String)

我通过如下更改代码使其工作:

public class Test {

 interface Strategy<T> {
  void execute(T t);
 }

 public static class DefaultStrategy<T> implements Strategy<T> {
   @Override
   public void execute(T t) {}

 }

 public static class Client<T> {
   private Strategy<T> a;

   public void setStrategy(Strategy<T> a) {
     this.a = a;
   }

   private void run(T t) {
     a.execute(t);
   }
 }

 public static void main(String[] args) {
   Client<String> client = new Client<String>();
   client.setStrategy(new DefaultStrategy<String>());
   client.run("hello world");
 }
}

但我想了解为什么原来的方法不起作用。

最佳答案

答案很简单:不能使用未绑定(bind)的通配符。它只是意味着“未知对象”。

它没有给编译器提供任何信息。 “?”意味着任何类型,所以实际上它太通用了,没有任何意义。

看这里:http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html

如上所述:

Collection<?> c = new ArrayList<String>();
c.add(new Object()); // Compile time error

由于我们不知道 c 的元素类型代表什么,因此我们无法向其中添加对象。 add() 方法采用 E 类型的参数,即集合的元素类型。当实际类型参数为?时,它代表某种未知类型。我们传递给 add 的任何参数都必须是该未知类型的子类型。由于我们不知道那是什么类型,因此我们无法传入任何内容。唯一的异常(exception)是 null,它是每种类型的成员。

编辑:别担心,这是当您开始使用 java 通配符时的正常误解。这就是有界通配符(例如 <? extends Something> )存在的原因,否则通用通配符几乎毫无用处,因为编译器无法对其做出任何假设。

关于java - 泛型错误 : not applicable for the arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57044975/

相关文章:

java - 从 Jboss-as 7.1.1 中的 standalone.xml 外部化资源适配器配置

java - 如何设置 map 值类型的上限

java - 泛型 0 无法转换为 java.lang.Short

Java泛型通配符

Java Shell 命令未从当前目录运行

java - insert upto 中的语法错误?访问权限

java - Criteria API 忽略 JOIN

java - 用于参数化类型的类和泛型类型转换

c# - 运算符重载多态返回泛型集合

java - "Unexpected token"使用下界通配符 (Java)