How to pass empty list with type parameter?

14,636

Solution 1

Collections.emptyList() is generic, but you're using it in its raw version.

You can explicitly set the type-parameter with:

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

Solution 2

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

Share:
14,636
2787184
Author by

2787184

Updated on June 07, 2022

Comments

  • 2787184
    2787184 almost 2 years
    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 empty list with type parameter?

    compiler giving me error message:

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

    and if I try to cast with List then the error:

    Cannot cast from List< Object > to List< User >

    result.setData(new ArrayList<User>()); is working fine but I don't want to pass it.