This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
you are saying that this is a list of animals. It could be dog, cat or anything else. But you don't know what it actually is. So you can't add anything to this list. What you actually know is that the list contain animals. So you can retrieve elements from this list but you can't add any elements.
But when you say
List<? super Dog>
Here you are saying that this list is of a super type of Dog. It can be a direct super class like Animal or indirect super class like Object or it can be of Dog itself. So you are basically not sure. But one thing's for sure. The list is of a super type of Dog or Dog itself. So you can add elements of type dog or sub class of dog to the list. But you can't add animal objects to the list as the list might be of type Dog too and every animal is not a dog. Just see this
List<? super Dog> list = new ArrayList<Dog>();
list.add(new Animal()); //1, not allowed
If 1 was allowed, then we would have added an animal to a dog list. But an animal is not a dog. That's why it is not allowed...
[Edit: banu added one more question by editing his post )
List<? super Dog> dog=new ArrayList<Dog>();
Why this is not allowing to add Animal which is super type for Dog..
dog can point to any List which can hold Dog or its Super types. assume that at runtime you have received a list of Dog objects, If you are allowed to add Animal to the list you will end up with Animal object in Dog list
SCJP 1.5 94%.
The greatest glory in living lies not in never falling, but in rising every time we fall.
I think Ankit with his excellent response and Ramesh must have cleared your previous doubts.
As to why you can add null:
You can add null because you can assign null to a reference of any type. To simplify things a little, you can consider null to be a value of any reference type, so you can assign null to Integer, to Animal, to Object, etc. When you add null you will be adding a null reference of whatever type the collection actually is. No matter what that type is, you can add a null reference to the collection.
All code in my posts, unless a source is explicitly mentioned, is my own.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com