commons-user mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Ryan Bennetts <moneyista...@gmail.com>
Subject [collections] MultiValueMap with a custom value collection type
Date Wed, 26 Mar 2014 23:59:32 GMT
Hello all

I am having trouble understanding how to use a custom value collection type
with a MultiValueMap. I want to use the new generics-supported version, but
can't see how to do this without excessive casting, which seems to defeat a
lot of the purpose of using generics in the first place. I have posted this
issue on stackoverflow <http://stackoverflow.com/questions/22625575> but
thought I would ask here too.

I would like a MultiValueMap<http://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/map/MultiValueMap.html>which
takes a String as a key, and a collection of Strings as the value.
But:

   1. The keys should retain insertion ordering (so I create the
   multi-valued map by decorating a
LinkedHashMap<http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashMap.html>
   )
   2. The values should be unique for each key and retain insertion
   ordering (so I want the values Collection type to be a
LinkedHashSet<http://docs.oracle.com/javase/6/docs/api/java/util/LinkedHashSet.html>
   ).

The closest I can get is:

MultiValueMap<String, String> orderedMap = MultiValueMap.multiValueMap(
    new LinkedHashMap<String, Collection<String>>(),
    LinkedHashSet.class);

But that produces this error:

The method multiValueMap(Map<K,? super C>, Class<C>) in the type
MultiValueMap is not applicable for the arguments
(LinkedHashMap<String,Collection<String>>,
Class<LinkedHashSet>)

So now I am in generics hell. Any suggestions would be most welcome. One
suggestion I have received is to use:

@SuppressWarnings("unchecked")MultiValueMap<String, String> orderedMap
= MultiValueMap.multiValueMap(
    new LinkedHashMap<String, Collection<String>>(),
    (Class<LinkedHashSet<String>>)(Class<?>)LinkedHashSet.class);

This works but do I really have to do two casts? Is this really what the
api designers intended?

Prior to version 4.0, I accomplished that with the following:

MultiValueMap orderedMap = MultiValueMap.decorate(
    new LinkedHashMap<>(),
    LinkedHashSet.class);

Which is certainly simpler, but not type safe. But that requires casting
when I call put() and get() and so I'd like to be able to use the new
generic version provided by 4.0.

Thanks,

-- Ryan

Mime
  • Unnamed multipart/alternative (inline, None, 0 bytes)
View raw message