This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
I have a compilation error both in Java 1.5.0_16 and 1.6.0_10 with generics.
I wanted to add a string to a LinkedList with comaprable as the base class ( String does implement Comparable). I looked at the
SCJP 5 book by Katherine Sierra and it seems to say (to me at least ) that it should work-- please see page 620 onwards (chapter 7 --
she is talking about a class called TestWildcards )
The following class gives compilation error at line #6 ("list.add(dummy);") -- Please see below for code and errors.
Any help will be appreciated.
Thanks in advance
Compilation and error given below (similar errors, BTW)
using Java 5(1.5.0_16)
Now here you are saying that this is a list of elements which are a sub type of Comparable (or comparable). But you are not sure what is the actual type of this list. The actual type can be String, Integer etc. So the initialization can be
So now the compiler is not sure of the actual type of list. So now when you try to add String to the list, it disallows you. This is because the list may be of Integer. Then the code would look as
But this is wrong. This will defeat the whole purpose of generics (i.e. type safety). If this is allowed, the code is not type safe now. Now the question is how is the code not type safe. The list will return Comparable so there is no chance of exception
And if you use an explicit cast, then any runtime exception is your fault
But the problem will arise in this code
In this code there will be a ClassCastException on runtime at line 2. So if line 1 is allowed, compiler will fail to fulfill his promise of exception free collection uses. That's why line 1 shows compilation error...
In general, whenever your generic type is <?> or <? extends X> for some X, you can't add anything.
You can with <? super X> though, because you know that whatever the actual generic type is, it is X or something that you can assign instances of X to. For instance, <? super Integer> could mean <Integer>, <Number> or <Object>, and even <Serializable> or <Comparable> (because Integer implements those). No matter which one of these though, all of them allow Integer objects to be assigned to them.