gpt4 book ai didi

java - Java 中集合的泛型和通配符

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:12:59 26 4
gpt4 key购买 nike

在使用 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);
}
};
}

我在调用 hasdoesNotHave 时遇到编译错误:

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>>).

我是 Java 的新手,我不明白这个问题:java.util.Listjava.util.Listjava.lang.String extends java.lang.String,不是吗?

最佳答案

在你的例子中,hasdoesNotHave方法采用 Condition<? super List<? extends T>条件,不是 Condition<? super List<T>>当你从你的 Condition<List<T>> sameNamesAs 返回时方法。

您需要一个 Condition<List<? extends String>> 的实例类型(它是原始类型 Condition<? super List<? extends String>> 的子类):

private Condition<List<? extends String>> sameNamesAs(List<String> rhs) {
return new Condition<List<? extends String>>("same names as " + rhs) { ... };
}

我试着用下面的片段来说明这一点:

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);

关于java - Java 中集合的泛型和通配符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41125625/

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