I have been learning generics in Java. Although I understand the concepts regarding type inference, parameterized classes and methods, I came across a strange scenario while experimenting.
I have implemented a Box class which can be used to hold items of type T. I am using List as an internal data structure for this abstraction. Following is my code:
public class Box<T> {
private List<T> items;
public Box(){
items = new ArrayList<>();
}
public <T> void addItemToBox(T t){
items.add(t);
}
}
I am getting a compile time error at items.add(t) saying add(T) in List cannot be applied to (T). I am unable to figure out the cause of this error. Also, I don't understand why I can't add an item of type T to a list which is parameterized by T.