Question_1
class A {}
class B extends A {}
A aObj = new A();
B bObj = new B();
We know that below will result in class cast exception at runtime .
List<B> list_B = new ArrayList<B>();
list_B.add((B)aObj); //ClassCast exception
But
List<? extends A> list_4__A_AND_SubClass_A = new ArrayList<B>();
List<A> list_A = (ArrayList<A>)list_4__A_AND_SubClass_A;
list_A.add(aObj); // No exception here, Why?
Question_2
In a method like below
void method(List<? extends A> list_4__A_AND_SubClass_A){
//How do i find the passed list is of Type A or B ??
// To decide List<A> list_A = (ArrayList<A>)list_4__A_AND_SubClass_A;
// OR List<B> list_B = (ArrayList<B>)list_4__A_AND_SubClass_A;
}
UPDATE
Q_1
Better I should avoid referencing the collection like below for modification; Unless We are very sure about the passed list is type of A/B; to maintain the integrity on that list.
List<A> list_A = (ArrayList<A>)list_4__A_AND_SubClass_A;
Q_2
I think we can pass one more argument from the caller method to the calling method to maintain the integrity over the list while modification at calling method.
void method(List<? extends A> list_4__A_AND_SubClass_A, Class<? extends A> obj){
if (A.class.isAssignableFrom(obj)) {
List<A> list_A = (List<A>)list_4__A_AND_SubClass_A;
list_A.add(new A());
list_A.add(new B());
} else if (B.class.isAssignableFrom(obj)){
List<B> list_B = (List<B>)list_4__A_AND_SubClass_A;
//list_B.add(new A()); //only we can add B
list_B.add(new B());
}
}