Java Generics - Mixed Object Maps

Viewed 2605

I'm still getting used to Java Generics however I'm currently in the process of updating an application written prior to generics to use the latest version of java.

Problem is the code was not written with type safety in mind!

We have a whole bunch of Maps that basically hold various object types including strings. For example:

Map map = new HashMap();
map.put("key1", "String1");
map.put("key2", new Date());
map.put("key3", new CutsomClass());

Now I'm still struggling with the best way to handle these without getting into refactoring a whole lot of code. Refactoring is not an option at this time.

Currently I can't see anything past Map<String, Object> although Map<String, ? super Object> works but I think its essentially the same thing ?

7 Answers

Looks like you want to quickly port the old code in and also you want to move the old code towards strict type safety without refactoring a large code base. Keep your old code by porting it in using this:

Map<String, Object> oldMapPorted = new HashMap<>();

New code written in this app can use a technique like this for strict type safety:

Map<String, Date> newMapDates = new HashMap<>(); 
Map<String, String> newMapStrings = new HashMap<>(); 
Map<String, CustomClass> newCutsomClasses = new HashMap<>();

A new class can be created for future edits and enhancements while the old code still has the same potential instability as usual.

Related