简体   繁体   中英

How to pass empty list with 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 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.

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

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

The issue you're encountering is that even though the method emptyList() returns List, you haven't provided it with the type, so it defaults to returning List. You can supply the type parameter, and have your code behave as expected, like this:

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

Now when you're doing straight assignment, the compiler can figure out the generic type parameters for you. It's called type inference. For example, if you did this:

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

then the emptyList() call would correctly return a List.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM