Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 561
2787184 Avatar asked Nov 10 '15 12:11

2787184


People also ask

How do you pass an empty list as a parameter?

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.

How do you pass an empty array list?

There are two ways to empty an ArrayList – By using ArrayList. clear() method or with the help of ArrayList. removeAll() method.

How do you pass an empty list in Python?

Using square brackets [] Lists in Python can be created by just placing the sequence inside the square brackets [] . To declare an empty list just assign a variable with square brackets.

How do you pass an empty array list in java?

motif=new ArrayList(); will make the passed arraylist motif to be new instance of arraylist, and thus since its new , its empty. I have not use motif or number. Mot is string arraylist in another class (NewJFrame). When I call it in another class i-e with j.


2 Answers

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());
like image 118
Konstantin Yovkov Avatar answered Oct 17 '22 11:10

Konstantin Yovkov


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

like image 43
Emerson Cod Avatar answered Oct 17 '22 09:10

Emerson Cod