Imagine you have a method that processes the elements of a
The answer is no. A
Imagine you could upcast a
The problem arises when you insert elements into the
This is true for any kind of collection, not just
So what's the solution for it. Its solution is wildcards (click on link to read on wildcards).
List
, e.g. print out all elements in the List
. Here is how such a method could look:public void printElements(List<Object> elements){ for(Object o : elements){ System.out.println(o); } }
Could you call this method with a
List<String>
instance? The answer is no. A
List<String>
is not a subtype of List<Object>
. The reason is this: Imagine you could upcast a
List<String>
to a List<Object>
. It would not cause any problems to iterate each String
instance in the List
as an Object
. After all, a String
is a subtype of Object
.The problem arises when you insert elements into the
List
. In a List<Object>
instance you can insert any Object
instance, also non-String
elements. Thus, if you could upcast a List<String>
to a List<Object>
, you could now insert non-String
objects into the List
, meaning the type safety would be broken. This is true for any kind of collection, not just
List
's.So what's the solution for it. Its solution is wildcards (click on link to read on wildcards).
No comments:
Post a Comment