Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Generics - Mixed Object Maps

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 ?

like image 456
Dangerous Hamster Avatar asked May 19 '17 13:05

Dangerous Hamster


People also ask

How to create a generic map in Java?

In a generic Map you need to define the type of the key and the type of the value of object stored in the Map.you can set the specific type of both the keys and values in a generic Map instance. The syntax for creating a generic Map is given below.

How to create a generic map in Salesforce?

In a generic Map you need to define the type of the key and the type of the value of object stored in the Map.you can set the specific type of both the keys and values in a generic Map instance. The syntax for creating a generic Map is given below. Here K is the type of map key and V is the type of the value stored in the map.

What is the difference between HashMap and generic map?

What is Generic Map and how is it different from the term HashMap? The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics.

What are some examples of generics in Java?

For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics. Generic Map in simple language can be generalized as:


1 Answers

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.

like image 176
Michael Avatar answered Oct 13 '22 16:10

Michael