[英]Generics and wildcards with collections in Java
In a test class using AssertJ, I have code similar to the following: 在使用AssertJ的测试类中,我的代码类似于以下内容:
public void someTest() {
assertThat(getNames()).has(sameNamesAs(getExpectedNames()));
assertThat(getNames()).doesNotHave(sameNamesAs(getOtherNames()));
}
private List<String> getNames() {
return null;
}
private List<String> getExpectedNames() {
return null;
}
private List<String> getOtherNames() {
return null;
}
private Condition<List<String>> sameNamesAs(List<String> rhs) {
return new Condition<List<String>>("same names as " + rhs) {
@Override
public boolean matches(final List<String> lhs) {
return lhs.containsAll(rhs) && rhs.containsAll(lhs);
}
};
}
I get a compilation error on the calls to has
and doesNotHave
: 我对
has
和doesNotHave
的调用出现了编译错误:
has/doesNotHave
(org.assertj.core.api.Condition<? super java.util.List<? extends java.lang.String>>)
in AbstractListAssert cannot be applied
to
(org.assertj.core.api.Condition<java.util.List<java.lang.String>>).
I'm new to Java and I don't understand the problem: java.util.List
is a super-type of java.util.List
and java.lang.String
extends java.lang.String
, don't they? 我是新来的Java,我不明白的问题:
java.util.List
是一个超级型java.util.List
和java.lang.String
延伸java.lang.String
,不是吗?
In your case, the has
and doesNotHave
methods take a Condition<? super List<? extends T>
在你的情况下,
has
和doesNotHave
方法采用Condition<? super List<? extends T>
Condition<? super List<? extends T>
Condition<? super List<? extends T>
condition, not a Condition<? super List<T>>
Condition<? super List<? extends T>
条件,而不是Condition<? super List<T>>
Condition<? super List<T>>
as you are returning from your Condition<List<T>> sameNamesAs
method. 当您从
Condition<List<T>> sameNamesAs
方法返回时, Condition<? super List<T>>
。
You need an instance of the Condition<List<? extends String>>
您需要
Condition<List<? extends String>>
的实例 Condition<List<? extends String>>
type (it's a subclass of the original type Condition<? super List<? extends String>>
): Condition<List<? extends String>>
type(它是原始类型Condition<? super List<? extends String>>
的子类):
private Condition<List<? extends String>> sameNamesAs(List<String> rhs) {
return new Condition<List<? extends String>>("same names as " + rhs) { ... };
}
I tried to illustrate this with the following snippet: 我尝试使用以下代码段来说明这一点:
List<String> list = getNames();
// ELEMENT = String, ACTUAL = List<? extends ELEMENT>
ListAssert<String> assertThat = assertThat(list);
// by the signature, we have to pass Condition<? super ELEMENT> or Condition<? super ACTUAL>
// Condition<? super ACTUAL> = Condition<? super List<? extends String>>
Condition<List<? extends String>> condition = sameNamesAs(list);
// Condition<List<? extends String>> extends Condition<? super List<? extends String>>
assertThat.has(condition);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.