Generics and wildcards with collections in Java

故事扮演 提交于 2020-01-13 12:17:38

问题


In a test class using AssertJ, I have code similar to the following:

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
(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?


回答1:


In your case, the has and doesNotHave methods take a Condition<? super List<? extends T> condition, not a Condition<? super List<T>> as you are returning from your Condition<List<T>> sameNamesAs method.

You need an instance of the Condition<List<? extends String>> type (it's a subclass of the original 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);


来源:https://stackoverflow.com/questions/41125625/generics-and-wildcards-with-collections-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!