Creating a Commons Collections MultiValueMap with a custom value collection type

坚强是说给别人听的谎言 提交于 2019-12-05 09:39:32

I consulted the Apache Commons Collections mailing list, where it was explained to me that the interface for MultiValueMap is known to be lacking, but will be revamped in version 4.1 (see here for the JIRA issue and associated discussion).

So in the future we may have a better solution, but in the meantime, as Rohit Jain mentioned in his answer, we're just going to have to suppress some warnings. However, since the key aspect of type safety is for the MultiValueMap (not the custom collection type), the simplest way to achieve this is:

@SuppressWarnings({ "rawtypes", "unchecked" })
MultiValueMap<String, String> orderedMap = 
    MapUtils.multiValueMap(new LinkedHashMap(), LinkedHashSet.class);

Note the use of the MapUtils factory method, rather than the more direct MultiValueMap which I had used in my original question.

The problem is you need to pass a Class<LinkedHashSet<String>> as second argument. That you can't create directly. You need to do some cast.

This will work fine:

@SuppressWarnings("unchecked")
MultiValueMap<String, String> orderedMap = 
           MultiValueMap.multiValueMap(
                new LinkedHashMap<String, Collection<String>>(), 
                (Class<LinkedHashSet<String>>)(Class<?>)LinkedHashSet.class
           );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!