相关疑难解决方法(0)

泛型方法上的多个通配符使Java编译器(和我!)非常混淆

让我们首先考虑一个简单的场景(请参阅ideone.com上的完整源代码):

import java.util.*;

public class TwoListsOfUnknowns {
    static void doNothing(List<?> list1, List<?> list2) { }

    public static void main(String[] args) {
        List<String> list1 = null;
        List<Integer> list2 = null;
        doNothing(list1, list2); // compiles fine!
    }
}
Run Code Online (Sandbox Code Playgroud)

这两个通配符是不相关的,这就是为什么你可以doNothing用a List<String>和a 调用List<Integer>.换句话说,两者?可以指代完全不同的类型.因此,以下不编译,这是预期的(也在ideone.com上):

import java.util.*;

public class TwoListsOfUnknowns2 {
    static void doSomethingIllegal(List<?> list1, List<?> list2) {
        list1.addAll(list2); // DOES NOT COMPILE!!!
            // The method addAll(Collection<? extends capture#1-of ?>)
            // in the type List<capture#1-of …
Run Code Online (Sandbox Code Playgroud)

java generics compiler-errors wildcard

58
推荐指数
1
解决办法
7197
查看次数

为什么我不能将子列表传递给接受List <?的方法?扩展父>?

我有一个名为FamilyHistoryPersonModel扩展名为的类的类PersonModel.

    MapValue mapValue = new MapValue("relatives",
            new GenericType<FamilyHistoryPersonModel>() {},
            new GenericType<List<FamilyHistoryPersonModel>>() {}  //error here
    );
Run Code Online (Sandbox Code Playgroud)

构造函数:

    private MapValue(String pluralUrl, GenericType<? extends PersonModel> singleResultGenericType, GenericType<List<? extends PersonModel>> listResultGenericType) {
        this.pluralUrl = pluralUrl;
        this.singleResultGenericType = singleResultGenericType;
        this.listResultGenericType = listResultGenericType;
    }
Run Code Online (Sandbox Code Playgroud)

错误:

cannot find symbol
symbol  : constructor MapValue(java.lang.String,<anonymous com.sun.jersey.api.client.GenericType<com.models.FamilyHistoryPersonModel>>,<anonymous com.sun.jersey.api.client.GenericType<java.util.List<com.models.FamilyHistoryPersonModel>>>)
location: class com.rest.v2.resource.CreatePersonModelIntegrationTest.MapValue
Run Code Online (Sandbox Code Playgroud)

为什么我收到此错误?我如何解决它?我不想改变构造函数来接受GenericType<List<FamilyHistoryPersonModel>> listResultGenericType

我使用的是JDK 1.6

java generics

3
推荐指数
1
解决办法
65
查看次数

标签 统计

generics ×2

java ×2

compiler-errors ×1

wildcard ×1