Java unchecked cast from object to list 

Joined:
04/09/2007
Posts:
753

July 11, 2011 12:24:10    Last update: July 11, 2011 12:25:44
This code snippet
import java.util.*;
public class UncheckedCast {
    public static void main(String[] args) {
	Object o = returnStringOrList();
	if (o instanceof List<String>) { // compilation fails
	    List<String> a = (List<String>) o; // unchecked cast
	    System.out.println("List:");
	    for (Object o2: a) {
		System.out.println("\t" + o2);
	    }
	}
	else {
	    System.out.println("String: " + o);
	}
    }

    private static Object returnStringOrList() {
	Random r = new Random();
	if (r.nextInt(2) > 0) {
	    return "string";
	}
	else {
	    return Arrays.asList(new String[] { "1", "2", "3" });
	}
    }
}

fails with a compilation error and a warning:
$ javac -Xlint:unchecked UncheckedCast.java
UncheckedCast.java:5: illegal generic type for instanceof
	if (o instanceof List<String>) {
	                     ^
UncheckedCast.java:6: warning: [unchecked] unchecked cast
found   : java.lang.Object
required: java.util.List<java.lang.String>
	    List<String> a = (List<String>) o;
	                                    ^
1 error
1 warning


Because List<String> is not a reifiable type, the Java Runtime does not have enough information to verify the type or do the type casting. This is fixed by changing List<String> to List<?> (or to the raw type List):
public static void main(String[] args) {
    Object o = returnStringOrList();
    if (o instanceof List<?>) {
	List<?> a = (List<?>) o;
	System.out.println("List:");
	for (Object o2: a) {
	    System.out.println("\t" + (String) o2);
	}
    }
    else {
        System.out.println("String: " + o);
    }
}

Share |
| Comment  | Tags