ArrayList<StringBuilder> al = new ArrayList<>(
Arrays.asList(new StringBuilder[]{
new StringBuilder("Oracle"),
new StringBuilder("Java"),
new StringBuilder("Sun"),
new StringBuilder("DataBase")}));
StringBuilder[] al2array = (StringBuilder[]) al.toArray();
If al.toArray()
returns an Object[]
which i know that its actually a StringBuilder[]
, then why cannot i cast it?
You most certainly can cast a variable typed as Object[]
to one typed as StringBuilder[]
. The compiler will not complain, and it will execute without error, IF the source reference does indeed reference a StringBuilder[]
.
public class ArrayCastTest {
public static void main(String[] argv) {
Object[] objArray;
StringBuilder[] sbArray;
objArray = getArray();
sbArray = (StringBuilder[]) objArray;
System.out.println(sbArray.toString());
}
public static Object[] getArray() {
return new StringBuilder[5];
}
}
This executes without error:
C:\JavaTools>javac ArrayCastTest.java
C:\JavaTools>java ArrayCastTest
[Ljava.lang.StringBuilder;@76f4da6d
C:\JavaTools>
The important thing to understand is that cast is "overloaded" -- it transforms simple values (like int
to char
) but it does not transform object references -- it only changes the declared type of the reference. The problem is that ArrayList.toArray()
returns an Object[]
. To get your Object[]
into a StringBuilder[]
use System.arraycopy.