Bizarre typing exception when using Arrays.copyOf
I have a class A, and two subclasses of A called B and C.
When I try and use the following method I created, with arguments (B[], C), I get an ArrayStoreException. This would suggest that types are clashing, but I don't see how that's possible.
Could anyone enlighten me?
publicstatic A[] arrayAppend(A[] detailsArray, A details){
A[] newDetailsArray = Arrays.copyOf(detailsArray, detailsArray.length + 1);
newDetailsArray[detailsArray.length] = details;
return newDetailsArray;
}
Oh... I thought that because I'm specifying it to deal with A arrays, that would bypass the problem.If, instead of using Arrays.copyOf, I manually copy the elements over to a new A[], that should work then, shouldn't it?
Awesome, I've just changed it to the code below, and it works great.
Thank you everyone :o)
public static A[] arrayAppend(A[] detailsArray, A details) {
A[] newDetailsArray = new A[detailsArray.length + 1];
int i = 0;
for (; i < detailsArray.length; i++)
newDetailsArray[i] = detailsArray[i];
newDetailsArray[i] = details;
return newDetailsArray;
}
Your B[] array is really an array of B objects. Even if you create an array of B objects and assign it to a variable of type A[]:
A[] array = new B[10];
then the array is still an array of B objects, and you can't put a C object into it (because C is not a subclass of B). You will have to make your array an array of A objects:
A[] array = new A[10];
Ofcourse, you can then assign B objects to the elements, because B is a subclass of A:
array[0] = new B();
And also assigning C objects will work, because C is also a subclass of A:
array[1] = new C();
And your copy method will also work.