ArrayList<classA> aList = /*I then fill this array*/
ArrayList<classB> bList = /* I then fill this array too*/
/*Now put them both in the following ArrayList of Objects*/
ArrayList<Object> myObjs = new ArrayList<Object>();
myObjs.add(aList);
myObjs.add(bList);
/*The following two lines however fails at run time*/
ArrayList<classA> x = (ArrayList<classA>) myObjs.get(0);
ArrayList<classB> x = (ArrayList<classB>) myObjs.get(1);
I just read from another thread that “Downcasting is allowed when there is a possibility that it succeeds at run time “
can any one please tell me the problem of the above code ?
thank you very much!
From the Java Tutorials on Generics:
Consider the following method:
What type of argument does it accept? By looking at its signature, you can see that it accepts a single argument whose type is
Box<Number>. But what does that mean? Are you allowed to pass inBox<Integer>orBox<Double>, as you might expect? The answer is “no”, becaueBox<Integer>andBox<Double>are not subtypes ofBox<Number>.In other words: Even though
classAis a subclass ofObject,ArrayList<classA>is not a subtype ofArrayList<Object>.