How to pass an empty list with a type parameter?

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

How to pass an empty list with a type parameter?

the compiler gives me an error message:

The setData (List <User>) method in the Service type is not applicable for arguments (List <Object>)

and if I try to use the List, then the error:

Cannot be dropped from <Object> to List <User>

result.setData(new ArrayList<User>()); It works fine, but I do not want to transmit it.

+4
source share
3 answers

Collections.emptyList() is generic, but you use it in your original version.

You can explicitly set the type parameter with:

result.setData(Collections.<User>emptyList());
+9
source

simply  result.setData(Collections.<User>emptyList());

+6
source

, , , emptyList() List, , . , , , :

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

Now that you are doing the direct task, the compiler can figure out the type parameters for you. He called type inference. For example, if you did this:

 List<User> emptyList = Collections.emptyList();

then calling emptyList () will correctly return the list.

0
source

Source: https://habr.com/ru/post/1615244/


All Articles