Reputation: 1383
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.
Upvotes: 3
Views: 2723
Reputation: 31269
You've made a local redeclaration of generic type variable <T>
on your method addItemToBox
that shadows the one on class Box<T>
.
The <T>
on your method is not the same on List<T> items;
Your current code is 100% equivalent to:
public class Box<T> {
private List<T> items;
public Box(){
items = new ArrayList<>();
}
public <T2> void addItemToBox(T2 t){
items.add(t);
}
}
If you see it that way, it should be clear why your code fails to compile.
Solution: remove the <T>
in front of the method declaration
public void addItemToBox(T t)
Upvotes: 11