14

Give the following code:

public static void main(String[] args) {
        HashMap<String, String> hashMap = new HashMap<>();
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("longvalue", 5L);

        class TestMethodHolder {
            <T> T getValue(Map<String, Object> dataMap, String value) {
                return (T)dataMap.get(value);
            }
        }

        hashMap.put("test", new TestMethodHolder().<String>getValue(dataMap, "longvalue"));
        String value = hashMap.get("test"); // ClassCastException occurs HERE
        System.out.println(value);
    }

It is not surprising to me that this code compiles, but rather that the ClassCastException occurs on the get line as opposed to the put line above it, though I do have an educated guess as to what what may be occurring. Since generic types are erased during runtime, the cast in getValue() actually never occurs at runtime and is effectively a cast to Object. If the method would be implemented below as follows, then the runtime cast would occur and it would fail on the put line (as expected). Can anyone confirm this?

class TestMethodHolder {
        String getValue(Map<String, Object> dataMap, String value) {
            return (String)dataMap.get(value);
        }
    }

Is this a known flaw or oddity of using generics? Is it bad practice then to use the <> notation when calling methods?

Edit: I am using the default Oracle JDK 1.7_03.

Another implied question from above: Is the cast in the original getValue STILL occurring at runtime but the cast is actually to Object - or is the compiler smart enough to remove this cast from not occurring at runtime at all? This might explain the difference of where the ClassCastException is occurring that people are noticing when running it.

GreenieMeanie
  • 3,560
  • 4
  • 34
  • 39
  • It compiles and run because type erasure will make it a `Map` at runtime. Of course, you will get a `ClassCastException` because you're treating a `Long` as a `String` and that's wrong. – Luiggi Mendoza May 17 '13 at 14:06
  • @LuiggiMendoza I think OP knows this - see his "educated guess" section. – zw324 May 17 '13 at 14:08
  • You have an unchecked cast from Object to T in `return (T)dataMap.get(value);`. You are overruling the compiler here. – devconsole May 17 '13 at 14:11
  • @ZiyaoWei I guess the example is not the most correct since OP's using `Object` and any object reference can fall as `Object`. Also, on runtime, the code will be executed as `hashMap.put("test", someObject)` with no strong type here due to type erasure that will treat it as `HashMap`, that will obviously fail when trying to retrieve it as `String` because its real type is `Long`. – Luiggi Mendoza May 17 '13 at 14:14
  • I certainly wouldn't call it a "flaw"...clearly this should be considered unsafe. – Mark Peters May 17 '13 at 14:31
  • I have run the code... and the exception is not where the OP says it is in my environment. Has anyone else tested this? – Menelaos May 17 '13 at 14:33
  • @meewoK: I think you made the same mistake I did, look at the actual code to see which line fails (it's flagged with a comment). I thought it was suggested that the `CCE` was at the first `.get()`, not the later one. – Mark Peters May 17 '13 at 14:37
  • The exception is on the `put()` line, not the `get()` line. – GriffeyDog May 17 '13 at 14:39
  • @GriffeyDog: Really? For me it's on the second `get()` line. What compiler are you using? – Mark Peters May 17 '13 at 14:42
  • The the OP using eclipse or compiling through the command line? Not sure if it makes a difference. – Menelaos May 17 '13 at 14:48
  • I am using the default Oracle JDK 1.7_03. The exception does occur on the get line in my environment. – GreenieMeanie May 17 '13 at 15:09
  • @MarkPeters Eclipse Juno – GriffeyDog May 17 '13 at 16:25

3 Answers3

12

Line

return (T)dataMap.get(value);

generates an Unchecked cast warning and, per specification, the presence of any such warning makes your code type-unsafe. The ClassCastException occurs the first time you try to assign the type-unsafe result into a variable of the wrong type because this is the first time the compiled code has a type check.

Note that Eclipse's compiler inserts more type checks than mandated by the JLS so, if you compile within Eclipse, the hashMap.put invocation fails with CCE. The compiler knows that this call must have two String arguments and so is in a position to insert the type checks before the actual method call.

Exactly as you are guessing, if you replace the generic T with the specific String, then the type check occurs at that point—and fails.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436
2

Compiler depends on type safety to make assumptions and do transformations/optimizations. Unfortunately the type safety can be subverted through unchecked cast. If your program contains incorrect unchecked cast, it is unclear what the compiler should do. Ideally it should make a runtime check at the exact point of unchecked cast, in your example, when Object is casted to T. But that is impossible, due to erasure, which is not exactly part of the type system.

Everywhere else in your example, types are sound, so compiler can assume that getValue() really returns a String, it is unnecessary to double check. But it's also legal to do the check, as Eclipse compiler does (probably because it assigns the return value to a String local temp variable).

So the bad news is, if your program contains incorrect unchecked cast, its behavior is undefined.... So make sure all your unchecked casts are correct, through rigorous reasoning.

A good practice is to check all unchecked casts so you can legitimately suppress the unchecked warning. For example

        <T> T getValue(Map<String, Object> dataMap, String value, Class<T> type) 
        { 
            Object value = dataMap.get(value);
            if(value!=null && !type.isInstance(value))  // check!
                throw new ClassCastException();

            @SuppressWarning("unchecked")
            T t = (T)value;  // this is safe, because we've just checked
            return t;
        }

See my answer to a similar question: Lazy class cast in Java?

Community
  • 1
  • 1
ZhongYu
  • 19,446
  • 5
  • 33
  • 61
  • In real code though you can use a somewhat shorter solution: `Object value = dataMap.get(name); return type.cast(value);`. – biziclop May 26 '15 at 19:37
0

This type information is erased during compilation (see Neal Gafter's "Reified Generics for Java").

On a practical note, you can guard your collections using the Collections utility methods:

Class<String> type = String.class;
Map<String, String> hashMap = new HashMap<>();
Map<String, String> map = Collections.checkedMap(hashMap, type, type);

Map rawType = map; // pre-Java 1.5 code knows nothing about generics
rawType.put(1, 2); // throws ClassCastException at runtime
McDowell
  • 107,573
  • 31
  • 204
  • 267