We know that parameterized types (in Java) are invariant, which implies that, for example, even though Integer is a subtype (subclass) of Number, List is not a subtype of List. Let's see how this impacts you code. Assume we have a class named Bucket declared below:
public class Bucket{ public void add(E e){...}; public void addAll(Listlist){ for(E e : list) { add(e); } } }
If you would try to do the following:
BucketnumberBucket = new Bucket List(); integers = new ArrayList ... numberBucket.addAll(integers);();
you get the error:
The method addAll(List
How can we get out of this? Easy, by using a bounded wildcard type:
public void addAll(List list){ for(E e : list) { add(e); } }
No comments:
Post a Comment