Prithvi Sehgal wrote:Hi,
I doubt that we can add anything to the list. The reference has to be used to call methods so that w can get
polymorphic behavior. If you want to add something to the list, you got to change it to somewhat
If we are mantaining Dog,Cat, Animal heirarchy
k fine List<? super Dog> animalList for adding Dog or sub-type of Dog .What about List<? extends Dog> animalList you mean its impossible to add objects for animallist .If so why?If not how?I hope this discussion will be closed with your coming reply.
Hope this helps
Prithvi Sehgal wrote:Tell me that,
What will happen if we stored something like a class D object which extends from B and is a sibling to C and the
arrayList which is being passed is of type C. What will happen then? Wrong type will be added to the collection
With array type information exists at run-time and if even we add a wrong type inside that array, we have got something
like ArrayStoreException. So you cannot add any wrong-type into the arrays. What about generics. No such exception exists because at
run-time JVM has no information about the type of the list. At run-time it behaves as a normal Pre-Java 5 list. Okay if it would have allowed you
to store that wrong type into the collection, what will happen when you will try to get something out of the list thinking that it is of type but it
turned out to be D. At that time you are dead.
Generics only provides compile time safety, not run-time.
By making it sure that you don't add anything wrong into the list, it is saving you from future disaster.
Still confused or want to give you a more detailed example?
Think about my reasons.
Prithvi Sehgal wrote:Hello,
Please have a look at GenericsConfusion
I have tried to explain the concept, if still don't understand. Refer back.
Hope this helps,