Java中具有集合的泛型和通配符 [英] Generics and wildcards with collections in Java

查看:126
本文介绍了Java中具有集合的泛型和通配符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用AssertJ的测试类中,我具有类似于以下内容的代码:

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

在调用hasdoesNotHave时出现编译错误:

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

我是Java的新手,我不理解这个问题:java.util.Listjava.util.List的超类型,而java.lang.Stringjava.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?

推荐答案

在您的情况下,hasdoesNotHave方法采用Condition<? super List<? extends T>条件,而不是Condition<? super List<T>>,因为您要从方法.

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.

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

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

这篇关于Java中具有集合的泛型和通配符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆