Casting to generic type in Java doesn't raise ClassCastException?

Posted by Kip on Stack Overflow See other posts from Stack Overflow or by Kip
Published on 2010-05-04T16:45:36Z Indexed on 2010/05/04 16:48 UTC
Read the original article Hit count: 351

Filed under:
|
|

I have come across a strange behavior of Java that seems like a bug. Is it? Casting an Object to a generic type (say, K) does not throw a ClassCastException even if the object is not an instance of K. Here is an example:

import java.util.*;
public final class Test {
  private static<K,V> void addToMap(Map<K,V> map, Object ... vals) {
    for(int i = 0; i < vals.length; i += 2)
      map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException!
  }
  public static void main(String[] args) {
    Map<String,Integer> m = new HashMap<String,Integer>();
    addToMap(m, "hello", "world"); //No exception
    System.out.println(m.get("hello")); //Prints "world", which is NOT an Integer!!
  }
}

© Stack Overflow or respective owner

Related posts about java

Related posts about generics