开发者

How to iterate through google collections' Multimap<?, Object>?

开发者 https://www.devze.com 2022-12-16 15:08 出处:网络
Before using google collections I had something similar to next code: private Set<A> aSet = ...;

Before using google collections I had something similar to next code:

private Set<A> aSet = ...;
private Set<B> bSet = ...;

public Foo getFoo (Map<?, List<Bar>> bars, Set<?> set) {
   for (Object item : set) {
      for (Bar bar : bars.get (item)) {
          //build foo;
      }
   }
   ...
}

and I was able to make calls like these:

Map<A, List<Bar> aMap = getAMap ();
Foo f1 = getFoo (aMap, aSet);
Map<B, List<Bar> bMap = getBMap ();
Foo f2 = getFoo (bMap, bSet);

Now, with Multi开发者_StackOverflow社区map, I cannot do the same:

public Foo getFoo (Multimap<?, List<Bar>> bars, Set<?> set) {
   for (Object item : set) {

      // compile error: get(capture#621 of ?) in Multimap ... cannot be applied to java.lang.Object
      for (Bar bar : bars.get (item)) {
          //build foo;
      }
   }
   ...
}


Try this:

public <T> Foo getFoo (Multimap<T, List<Bar>> bars, Set<T> set) {
   for (T item : aSet) {

      // compile error: get(capture#621 of ?) in Multimap ... cannot be applied to java.lang.Object
      for (Bar bar : bars.get (item)) {
         //build foo;
      }
   }
   ...
}

EDIT:

If you see the javadoc for both classes, you will realize that the javadoc for Map is:

V get(Object key) 

and for MultiMap is:

Collection<V> get(K key) 

See that the parameter for Map is not generified.

The MultiMap is better for generic, but Map is designed so it has backward compability with previous Map from Java 1.4.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号