Skip to Main Content

Java APIs

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

cast problem with generic ArrayList and toArray

843793Jan 19 2008 — edited Jan 19 2008
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)
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Feb 16 2008
Added on Jan 19 2008
4 comments
252 views