0

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?

Bacteria
  • 8,406
  • 10
  • 50
  • 67

2 Answers2

1

One word: Heredity.

A String is an Object, but an Object don't have to be a String. The ordinary example is the point and the particle. A particle is a point with mass. A particle is a point with something more. So you can say that a particle is a point with mass zero, but not the point is a particle. You have a collection of point, but then you want that the collection of point were a collection of particle. This is the mistake with List<Object> and List<String>. The reverse is good, but that you try not.

Shondeslitch
  • 1,049
  • 1
  • 13
  • 26
1

Compiler doesn't let you to do this. You declared your list as List<Object> you can't assign it to String:

  List<Object> myObjectArrayList = new ArrayList<String>(); // doesn't compile

You have to use wildcards for it Java Generics (Wildcards).

Community
  • 1
  • 1
catch23
  • 17,519
  • 42
  • 144
  • 217
  • I already mentioned that I will get the compilation error :Type mismatch: cannot convert from List to List – Bacteria Apr 30 '15 at 21:47