0

I've used Joshua Bloch's heterogeneous container idea to type safely store/retrieve values. But I also am storing primitive types (which in the container are auto boxed to Object types), and am unable to retrieve the values as primitive types. The type.cast(value) appears to auto box the value back to an object (I had already converted to a double) at which point it cannot type cast back to a primitive.

Here is my code:

import java.util.LinkedHashMap;
public class TestHeterogeneous {

    static private LinkedHashMap<Class<?>, Object> elements = new LinkedHashMap<>();

    static public <T> void putElement(Class<T> type, T value) {
        elements.put(type, value);
    }
    static public <T> T getElement(Class<T> type) {
        double dValue = (double) elements.get(type);
        return type.cast(dValue);
    }

    public static void main(String[] args) {
        putElement(double.class, 12.345);
        System.out.println("double value: "+getElement(double.class));     
    }
}

Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.Double to double
    at java.lang.Class.cast(Class.java:3084)
    at tooldevelopment.TestHeterogeneous.getElement(TestHeterogeneous.java:14)

Thanks, I appreciate your help.

PM 77-1
  • 12,933
  • 21
  • 68
  • 111
  • Which exact line has the exception? from the error it looks as if the offending cast is actually the `(double)` not the `type.cast`. – wrschneider Nov 03 '13 at 00:58
  • have you tried `double dValue = (Double) elements.get(type);` – akf Nov 03 '13 at 01:02
  • 1
    Is it necessary for the heterogeneous container to support primitive types? Given that they need to be boxed anyway, why not just use `Double.class`? Anyway it doesn't make sense that the generic method `getElement` would have `double`-specific code. – Paul Bellora Nov 03 '13 at 01:16
  • Your stacktrace is obvious: your 'Class type' parameter is java.lang.Double. It cannot be cast to primitive 'double' type. – IgorGanapolsky Mar 03 '14 at 20:10
  • 2
    A belated thank you for your responses. I found @Paul's response most helpful and have used Double.class in my test as well as shortening my getElement method to just one line `return type.cast(elements.get(type));` – John E. Miller Oct 16 '14 at 00:22

0 Answers0