Unchecked Assignment Hash Map

Well, first of all, you're wasting memory with the new creation call. Your second line completely disregards the reference to this created hashmap, making it then available to the garbage collector. So, don't do that, use:

Secondly, the compiler is complaining that you cast the object to a without checking if it is a . But, even if you were to do:

You would probably still get this warning. The problem is, returns , so it is unknown what the type is. Converting it to directly would not cause the problem with the second case (and perhaps there would not be a warning in the first case, I'm not sure how pedantic the Java compiler is with warnings for Java 5). However, you are converting it to a .

HashMaps are really maps that take an object as a key and have an object as a value, if you will. Thus, there is no guarantee that when you get your bean that it can be represented as a because you could have because the non-generic representation that is returned can have any objects.

If the code compiles, and you can execute without any errors, don't worry about this warning. But if the map isn't completely of string keys to string values, you will get a at runtime, because the generics cannot block this from happening in this case.

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. is an attempt to do that.

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) Returningis sufficient (rather than returning)
  • (5) The key and value type args are not generic (like )

(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 was passed into a I haven't been able to figure out how to return a . So I return a .

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

Despite those limitations can you see any problems with this java 1.5 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. :)

Usage code block:

Methods code block:

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.

javagenericscasting

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *