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.
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.
There are two ways to empty an ArrayList – By using ArrayList. clear() method or with the help of ArrayList. removeAll() method.
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.
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.
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());
simply
result.setData(Collections.<User>emptyList());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With