Java Generics - Mixed Object Maps
I'm still struggling with the best way to handle these without getting into refactoring a whole lot of code
So don't change them at all. The raw types - that is, the non-generic types - are still technically valid. It's not ideal and it will generate a compiler warning but the code will work (well, work as well as it ever did).
All classes extend Object
so you can put any value you want into the following map:
Map<String, Object> map = new HashMap<>();
You get an additional guarantee that the key is a string, so its somewhat better than using the raw type.
Basically though, you should really try to avoid using a map if you can't define the type of the key or the value.
As Michael suggested Map<String, Object> map = new HashMap<>();
is a first step.
However, it assumes that you have only String
as keys and you will probably need to cast objects you get from the map.
I think that a second step would be to split this map into multiple maps declaring a more specific type :
Map<String, Date> mapDates = new HashMap<>();
Map<String, String> mapStrings = new HashMap<>();
Map<String, CustomClass> mapCutsomClasses = new HashMap<>();
As of now, you can only replace the raw type Map
with Map<String, Object>
; but that type information is close to "useless". Unless you refactor your whole component to deal with different map objects, there isn't much you can do. Of course, you can get rid of the type warnings, but you still have to do instanceof
checks each time you access a Map value.
On way out of this: assuming that number of "value" types is known and reasonably small, you could create a bunch of helper methods that go like:
public Map<String, Date> extractDates(Map<String, Object> allValues) {
...
This method could implement a "wrapper" around the allValues
map that only provides those map entries that are actually Date objects.
Meaning: you keep your current map object, but you provide "more specialized" views on that map. That allows you to write new code exploiting the additional type information.
But of course, this doesn't come for free. It adds certain complexity, and defining the exact details of such "view maps" might turn out to be rather complicated.