In the code below why do the first two casts
(String[]) oa;
succeed while the third one fails ?
import java.util.ArrayList;
import java.util.Arrays;
class cast {
public static void main(String[] args) {
Object[] oa = args;
//we can cast an Object[] to a String[] if the elements of the Object[] are strings
String[] sa = (String[]) oa;
ArrayList<String> als = new ArrayList<String>(Arrays.asList((String [])oa));
als.toArray((String[]) oa);
oa = als.toArray();
//why does this get a ClassCastException given that the same casts above works
sa = (String[]) oa;
}
}
$ javac -g -Xlint:unchecked cast.java
$ java cast hello world
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
at cast.main(cast.java:15)