gpt4 book ai didi

Java 泛型 : not applicable methods

转载 作者:搜寻专家 更新时间:2023-11-01 03:00:11 24 4
gpt4 key购买 nike

我有这门课:

public abstract class SlightExpression<T> extends Expression<T> {
public BooleanExpression eq(Expression<? super T> right) {}
}

去想下一句:

    SlightExpression<?> left;
SlightExpression<?> right;
//...

left.eq(right);

Java 告诉我:

The method eq(capture#19-of ?) in the type SlightExpression<capture#19-of ?> 
is not applicable for the arguments (SlightExpression<capture#20-of ?>)

但是,

public abstract class StringExpression extends SlightExpression<String> {}

然后,Java 什么也没告诉我。

StringExpression s, f;
s.eq(f);

我不明白这种行为。

最佳答案

当 left 和 right 被声明为

SlightExpression<?> left;
SlightExpression<?> right;

你可以给他们赋值SlightExpression具有不同的参数类型。例如:

left = new SlightExpression<Integer>();
right = new SlightExpression<String>();

现在,您不能传递 SlightExpression<String>eq SlightExpression<Integer> 的方法实例。

另一方面,在您的第二个代码段中,两个实例都是 SlightExpression<String> 的子类, 因此将一个实例作为参数传递给 eq 是没有问题的另一个实例的方法。

为了更好地理解这个概念,您可以将它应用到更广为人知的类中。例如:

List<?> l1 = new ArrayList <String> ();
List<?> l2 = new ArrayList <Integer> ();
l1.addAll (l2); // this doesn't pass compilation, since you can't add Integer elements to
// a List<String>

List<?> l1 = new ArrayList <String> ();
List<?> l2 = new ArrayList <String> ();
l1.addAll (l2); // this doesn't pass compilation too, since the compiler doesn't know that
// l1 and l2 will refer to Lists of the same element type when addAll is
// invoked

另一方面,此代码段将通过编译,因为编译器发现两个列表具有相同的元素类型:

List<String> l1 = new ArrayList <String> ();
List<String> l2 = new ArrayList <String> ();
l1.addAll (l2);

关于Java 泛型 <? super T> : not applicable methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37044458/

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