2

I have a data structure Map < String, Map < ConfigKey, ConfigValue<Object > > >. This is like a Map of "namespace" to Map of "key" to "value". My parser reads config file and dynamically decides if the value should be treated as String or ArrayList.

I see error adding ArrayList to above data structure. Please show me how to fix this.

private Map<String, Map<ConfigKey, ConfigValue<Object>>> configuration = new HashMap<String, Map<ConfigKey, ConfigValue<Object>>>();
:
configuration.get(groupName).put(new ConfigKey(key), new ConfigValue<Object>(override, value)); // works
:
configuration.get(groupName).put(new ConfigKey(key), new ConfigValue<List>(override, Arrays.asList(values))); // does not work
DanglingPointer
  • 261
  • 1
  • 6
  • 19

1 Answers1

3
ConfigValue<List> is not a ConfigValue<Object>.

Read more about covariance and contravariance in Java or in programming in general.

This would fix it

private Map<String, Map<ConfigKey, ConfigValue<? extends Object>>> configuration = new HashMap<String, Map<ConfigKey, ConfigValue<? extends Object>>>();

or

Map<String, Map<ConfigKey, ConfigValue<?>>> 

And please avoid raw-types in your code.

Community
  • 1
  • 1
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77