May be very stupid question but still I want to clear this concept. Please help me.
List<Object> myObjectArrayList=new ArrayList<Object>();
Object myObject=new Object();
myObjectArrayList.add(obj);
myObjectArrayList.add("My String");
Here using Java's Generics features I set the type of the collection as String. But myObjectArrayList can add myObject into the list as Object class is the parent class of all the classes in Java by default. Now
List<String> myStringArrayList = new ArrayList<String>();
myObjectArrayList = myStringArrayList;
When I am doing myObjectArrayList = myStringArrayList; I am getting the compilation error:
Type mismatch: cannot convert from List<String> to List<Object>
Why not Java allow to assign a List< String > object into a List< Object >? My question is if I have a list of parent class and list of child class, why Java does not allow us to assign the child class list object into parent class list object?