A list of XYZ is not a list of X, even if XYZ inherits from or implements X.Java Generics do not allow that. To be more explicit, change XYZ and X by real objects (cats and animals) like it was said in the so link
Difference in the type of "Array of Objects" AND "ArrayList of same Objects"? [duplicate]
-
13-07-2023 - |
سؤال
I am unable to understand the difference in the type of "Array of Objects" AND "ArrayList of same Objects". For example I have Interface X:
public interface X {
public void implemntX();
}
Class XYZ implementing X:
public class XYZ implements X{
@Override
public void implemntX() {
// TODO Auto-generated method stub
}
}
Following codes works perfect:
X arraryOfX[] = new XYZ[10];
if(arraryOfX instanceof XYZ[]){
System.out.println("arraryOfX is instanceOF XYZ[]");
}else{
System.out.println("arraryOfX is NOT instanceOF XYZ[]");
}
Output: arraryOfX is instanceOF XYZ[]
But following line of code gives me compile time error:
ArrayList<X> arrayListOFX = new ArrayList<XYZ>();
ERROR: Type mismatch: cannot convert from ArrayList<XYZ> to ArrayList<X>
To the best of my understanding, ArrayList internally uses array then why Type mismatch error is bubbling up?
المحلول
نصائح أخرى
Suppose you had class ABC implements X
you CAN add an instance of ABC to List<X>
but you CAN'T add it to ArrayList<XYZ>
.
Just because ArrayList is backed by an array, don't confuse the 2.
لا تنتمي إلى StackOverflow