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.
What is the difference between lin1 and line 2. Line 1 creates a error whereas line 2 does not. As far i understood generic type of argument and parameter should be same thats why line one error is generated. What is happening at line 2 ? ?
Why to worry about things in which we dont have control, Why to worry about things in which we have control ! !
doc.checkAnimals((ArrayList < Animal > ) cats); means ArrayList<Animal> temp=cats; that is actually ArrayList<Animal> temp=new ArrayList<Cat>(); then it says its inconvertable types. Inconvertable means you cannot convert Cat list to Animal list. [ January 02, 2009: Message edited by: Punit Singh ]
ArrayList<Animal> animal = new ArrayList<Cat>(); //if this was allowed then following will create problems animal.add(new Dog()); //Oops we added a Dog into a Cat List
In addition to this if ArrayList<Animal> animal = new ArrayList<Animal>(); then animal.add(new Dog()); animal.add(new Cat()); allowed
Why ArrayList<Animal> animal = new ArrayList<Cat>(); not allowed ? As JVM has not runtime information about type of ArrayList, JVM will only knows that it is just an ArrayList means jvm will see this code:
and this code can take any object. So to avoid above condition mentioned by Ankit, compiler only allows type-safe conversions, such that ArrayList<Cat> can not contain new Dog();. Think in terms of compiler, you will grasp it easily. Again read K&B book for this topic and do some meditation over this.
Well I was trying to avoid telling this as it might be confusing but it is required now.
If you add a Dog to the Cat list, it will not be a problem and you can do this using legacy code
When you added a dog to the cat list, then there is no exception as the list is actually a raw list for the JVM. But then you will get an exception when you get the element from the Cat list as Dog is not a Cat...