1

Casting, instanceof, and @SuppressWarnings("unchecked") are noisy. It would be nice to stuff them down into a method where they won't need to be looked at. CheckedCast.castToMapOf() is an attempt to do that.

castToMapOf() is making some assumptions:

  • (1) The map can't be trusted to be homogeneous
  • (2) Redesigning to avoid need for casting or instanceof is not viable
  • (3) Ensuring type safety in an fail early manner is more important than the performance hit
  • (4) Returning Map<String,String> is sufficient (rather than returning HashMap<String, String>)
  • (5) The key and value type args are not generic (like HashMap<String, ArrayList<String>>)

(1), (2) and (3) are symptoms of my work environment, beyond my control. (4) and (5) are compromises I've made because I haven't found good ways to overcome them yet.

(4) Is difficult to overcome because even if a HashMap.class was passed into a Class<M> I haven't been able to figure out how to return a M<K, V>. So I return a Map<K, V>.

(5) Is probably an inherent limitation of using Class<T>. I'd love to hear alternative ideas.

Despite those limitations can you see any problems with this code? Am I making any assumptions I haven't identified? Is there a better way to do this? If I'm reinventing the wheel please point me to the wheel. :)

public class CheckedCast {

    public static final String LS = System.getProperty("line.separator");

    /** Check all contained items are claimed types and fail early if they aren't */
    public static <K, V> Map<K, V> castToMapOf( 
            Class<K> clazzK,    
            Class<V> clazzV,
            Map<?, ?> map) {

        for ( Map.Entry<?, ?> e: map.entrySet() ) {
            checkCast( clazzK, e.getKey() );            
            checkCast( clazzV, e.getValue() );            
        }

        @SuppressWarnings("unchecked")
        Map<K, V> result = (Map<K, V>) map;        
        return result; 
    }

    /** Check if cast would work */
    public static <T> void checkCast(Class<T> clazz, Object obj) {
        if ( !clazz.isInstance(obj) ) {
            throw new ClassCastException(
                LS + "Expected: " + clazz.getName() +
                LS + "Was:      " + obj.getClass().getName() +
                LS + "Value:    " + obj
            );
        }
    }

    public static void main(String[] args) {

        // -- Raw maps -- //

        Map heterogeneousMap = new HashMap();
        heterogeneousMap.put("Hmm", "Well");
        heterogeneousMap.put(1, 2); 

        Map homogeneousMap = new HashMap();
        homogeneousMap.put("Hmm", "Well");

        // -- Attempts to make generic -- //

        //Unsafe, will fail later when accessing 2nd entry
        @SuppressWarnings("unchecked") //Doesn't check if map contains only Strings
        Map<String, String> simpleCastOfHeteroMap = 
                    (Map<String, String>) heterogeneousMap;  

        //Happens to be safe.  Does nothing to prove claim to be homogeneous.
        @SuppressWarnings("unchecked") //Doesn't check if map contains only Strings
        Map<String, String> simpleCastOfHomoMap = 
                    (Map<String, String>) homogeneousMap;  

        //Succeeds properly after checking each item is an instance of a String
        Map<String, String> checkedCastOfHomoMap = 
                    castToMapOf(String.class, String.class, homogeneousMap);

        //Properly throws ClassCastException
        Map<String, String> checkedCastOfHeteroMap = 
                    castToMapOf(String.class, String.class, heterogeneousMap); 
        //Exception in thread "main" java.lang.ClassCastException: 
        //Expected: java.lang.String
        //Was:      java.lang.Integer
        //Value:    1
        //    at checkedcast.CheckedCast.checkCast(CheckedCast.java:14)
        //    at checkedcast.CheckedCast.castToMapOf(CheckedCast.java:36)
        //    at checkedcast.CheckedCast.main(CheckedCast.java:96)

    }
}

Some reading I found helpful:

Generic factory with unknown implementation classes

Generic And Parameterized Types

I'm also wondering if a TypeReference / super type tokens might help with (4) and (5) and be a better way to approach this problem. If you think so please post an example.

Community
  • 1
  • 1
candied_orange
  • 7,036
  • 2
  • 28
  • 62

1 Answers1

2

The code looks good, but I would add an assumption: (6) the raw reference will never be used anymore. Because if you cast your Map to a Map<String, String>, then put an integer to the raw map, you may get surprises.

Map raw = new HashMap();
raw.put("Hmm", "Well");
Map<String, String> casted = castToMapOf(String.class, String.class, raw); // No error
raw.put("one", 1);
String one = casted.get("one"); // Error

Instead of casting the map, I would create a new one (maybe a LinkedHashMap to preserve order), casting each object as you add them to the new map. This way, the ClassCastException would be thrown naturally, and the old map reference can still be modified without affecting the new one.

WilQu
  • 7,131
  • 6
  • 30
  • 38
  • I could argue that I can avoid the reference simply by putting a getter method where you put raw but I think what you're really saying is I'm not saving much over just doing: HashMap hmss = new HashMap(raw); Which I think is a good point. We're only copying the references after all. – candied_orange Sep 02 '14 at 10:04
  • @CandiedOrange creating a new map can be costly if the map is very big and/or if the method is called very often, but according to (3) it doesn't matter :) However, if you can make sure that the raw reference is never used, then your code is fine. – WilQu Sep 02 '14 at 11:34
  • Yeah with (3) we're looping thru anyway. A new HashMap just costs a little bit of memory (Map.size() times the size of a reference: 32 or 64 bits) on top of the CPU hit we'd have anyway and it solves the (4) problem. But ya know, another way to be sure the old raw isn't used after the cast would be set it to null right after casting, if it isn't about to go out of scope anyway. Then the only danger is it being held by whatever handed it to you. Which, if you're multi threaded, might be a big issue. Anyway, I still wish I knew how to solve (5) even with this. :) – candied_orange Sep 02 '14 at 13:44
  • Ran some tests and unfortunately new HashMap(raw) doesn't do the checks I'm after. It seems to just copy the references. So I'm back to needing castToMapOf(). What I could do is also add a checkedCopyMap() method. It would be the same as new HashMap(castToMapOf(raw)); – candied_orange Sep 03 '14 at 00:56
  • @CandiedOrange what I suggested is to add the objects one by one to the new map, casting each object each time. – WilQu Sep 03 '14 at 06:16
  • Sort of like the MapBuilder here?: http://stackoverflow.com/questions/2767212/casting-to-generic-type-in-java-doesnt-raise-classcastexception?rq=1 – candied_orange Sep 03 '14 at 09:49
  • @CandiedOrange yes exactly – WilQu Sep 04 '14 at 13:41