如何使用类型参数传递空列表?

278*_*184 5 java generics collections list

class User{
    private int id;
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

class Service<T> {
    private List<T> data;
    public void setData(List<T> data) {
        this.data = data;
    }
}

public class ServiceTest {
    public static void main(String[] args) {
        Service<User> result=new Service<User>();
        result.setData(Collections.emptyList()); // problem is here
    }
}
Run Code Online (Sandbox Code Playgroud)

如何使用类型参数传递空列表?

编译器给我错误信息:

参数类型中的方法setData(List <User>)不适用于参数(List <Object>)

如果我尝试使用List进行转换,那么错误:

无法从List <Object>强制转换为List <User>

result.setData(new ArrayList<User>()); 工作正常,但我不想通过它.

Kon*_*kov 12

Collections.emptyList() 是通用的,但你在它的原始版本中使用它.

您可以使用以下方法显式设置type-parameter:

result.setData(Collections.<User>emptyList());
Run Code Online (Sandbox Code Playgroud)


Eme*_*Cod 6

只是 result.setData(Collections.<User>emptyList());