views:

186

answers:

5

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!!
  }
}

Update: Thanks to cletus and Andrzej Doyle for your helpful answers. Since I can only accept one, I'm accepting Andrzej Doyle's answer because it led me to a solution that I think isn't too bad. I think it's a little better way of initializing a small Map in a one-liner.

  /**
   * Creates a map with given keys/values.
   * 
   * @param keysVals Must be a list of alternating key, value, key, value, etc.
   * @throws ClassCastException if provided keys/values are not the proper class.
   * @throws IllegalArgumentException if keysVals has odd length (more keys than values).
   */
  public static<K,V> Map<K,V> build(Class<K> keyClass, Class<V> valClass, Object ... keysVals)
  {
    if(keysVals.length % 2 != 0)
      throw new IllegalArgumentException("Number of keys is greater than number of values.");

    Map<K,V> map = new HashMap<K,V>();
    for(int i = 0; i < keysVals.length; i += 2)
      map.put(keyClass.cast(keysVals[i]), valClass.cast(keysVals[i+1]));

    return map;
  }

And then you call it like this:

Map<String,Number> m = MapBuilder.build(String.class, Number.class, "L", 11, "W", 17, "H", 0.001);
+5  A: 

Java generics use type erasure, meaning those parameterized types aren't retained at runtime so this is perfectly legal:

List<String> list = new ArrayList<String>();
list.put("abcd");
List<Integer> list2 = (List<Integer>)list;
list2.add(3);

because the compiled bytecode looks more like this:

List list = new ArrayList();
list.put("abcd");
List list2 = list;
list2.add(3); // auto-boxed to new Integer(3)

Java generics are simply syntactic sugar on casting Objects.

cletus
So, I guess there's no way to make my function work as intended? I tried using `vals[i] instanceof K` and `K.class.getName()` after posting this, but that gives syntax error. (I guess because there isn't really a `K` at runtime...)
Kip
A: 

Java generics only apply during compile time and not run time. The issue is the way you have implemented, java compiler does not get a chance to ensure type safety at compile time.

Since ur K,V never say they extend any particular class, during compile time java has no way to know it was supposed to be an integer.

If you change your code as following

private static void addToMap(Map map, Object ... vals)

it will give you a compile time error

Fazal
+1  A: 

Java's generics are done using "type erasure", meaning that at runtime, the code doesn't know you have a Map<String, Integer> -- it just sees a Map. And since you're converting the stuff to Objects (by way of your addToMap function's param list), at compile time, the code "looks right". It doesn't try to run the stuff when compiling it.

If you care about the types at compile time, don't call them Object. :) Make your addToMap function look like

private static<K,V> void addToMap(Map<K, V> map, K key, V value) {

If you want to insert multiple items in the map, you'll want to make a class kinda like java.util's Map.Entry, and wrap your key/value pairs in instances of that class.

cHao
Your addToMap example is basically the same thing as the Map.put() method. I was hoping I could initialize a Map in as compact a manner as possible. Oh well.
Kip
You can, but you'll give up type safety. Not worth it, IMO. And one of the reasons i prefer .net to Java these days.
cHao
+1  A: 

As cletus says, erasure means that you can't check for this at runtime (and thanks to your casting you can't check this at compile time).

Bear in mind that generics are a compile-time only feature. A collection object does not have any generic parameters, only the references you create to that object. This is why you get a lot of warning about "unchecked cast" if you ever need to downcast a collection from a raw type or even Object - because there's no way for the compiler to verify that the object is of the correct generic type (as the object itself has no generic type).

Also, bear in mind what casting means - it's a way of telling the compiler "I know that you can't necessarily check that the types match, but trust me, I know they do". When you override type checking (incorrectly) and then end up with a type mismatch, who ya gonna blame? ;-)

It seems like your problem lies around the lack of heterogenous generic data structures. I would suggest that the type signature of your method should be more like private static<K,V> void addToMap(Map<K,V> map, List<Pair<K, V>> vals), but I'm not convinced that gets you anything really. A list of pairs basically is a map, so contructing the typesafe vals parameter in order to call the method would be as much work as just populating the map directly.

If you really, really want to keep your class roughly as it is but add runtime type-safety, perhaps the following will give you some ideas:

private static<K,V> void addToMap(Map<K,V> map, Object ... vals, Class<K> keyClass, Class<V> valueClass) {
  for(int i = 0; i < vals.length; i += 2) {
    if (!keyClass.isAssignableFrom(vals[i])) {
      throw new ClassCastException("wrong key type: " + vals[i].getClass());
    }
    if (!valueClass.isAssignableFrom(vals[i+1])) {
      throw new ClassCastException("wrong value type: " + vals[i+1].getClass());
    }

    map.put((K)vals[i], (V)vals[i+1]); //Never throws ClassCastException!
  }
}
Andrzej Doyle
I was just hoping for a typesafe way to initialize a map in a one-liner, like in some other languages (i.e. Perl/PHP/Javascript) where you can do something like `map = (key1=>val1, key2=>val2, etc);`
Kip
Yep - you just can't do that, as the array has no compile-time type information and the generic parameters have no run-time type information. Passing around `Class<T>` parameters are about the only way you can tie the compile-time and run-time checks together.
Andrzej Doyle
+1  A: 

This is a fairly good explanation of what Generics do and don't do in Java: http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html

It is very very different from C#!

I think you were trying to do something like this? Where there's compile time safety for the pairs that you're adding to the map:

addToMap(new HashMap<String, Integer>(), new Entry<String,Integer>("FOO", 2), new Entry<String, Integer>("BAR", 8));

    public static<K,V> void addToMap(Map<K,V> map, Entry<K,V>... entries) {
        for (Entry<K,V> entry: entries) {
            map.put(entry.getKey(), entry.getValue());
        }
    }

    public static class Entry<K,V> {

        private K key;
        private V value;

        public Entry(K key,V value) {
            this.key = key;
            this.value = value;
        }

        public K getKey() {
            return key;
        }

        public V getValue() {
            return value;
        }
    }

Edit after comment:

Ahh, then perhaps all you're really looking for is this arcane syntax used to harass new hires who just switched to Java.

Map<String, Integer> map = new HashMap<String,Integer>() {{
  put("Foo", 1);
  put("Bar", 2);
}};
Affe
i was basically trying to initialize a map in a compact, typesafe one-liner. hoping to approach the simplicity of PHP's `map = (key1=>val1, key2=>val2, etc);`
Kip
There are obscure ways to sort of do that in java, see edited answer. Do realize that doing that is generally more on the 'clever' side of things than the 'sound software engineering practice' in many people's opinions :)
Affe
thanks, now that you mention it, i think i have seen that syntax before.
Kip