java - Creating a view of multiple Maps' entrySets -


i have iterable<map<? extends k, ? extends v>> , i'd provide view union of these maps' entry sets, i.e. set<map.entry<k, v>>.

i can construct new set (the cast triggers unchecked warning, compiles):

immutableset.builder<map.entry<k, v>> builder = immutableset.builder(); for(map<? extends k, ? extends v> map : chain) {   for(map.entry<? extends k, ? extends v> e : map.entryset()) {     builder.add((map.entry<k, v>) e);   } } return builder.build(); 

however requires copying sets, , doesn't stay in-sync backing maps. i've tried things like:

set<map.entry<k, v>> unionset = immutableset.of(); for(map<? extends k, ? extends v> map : chain) {   unionset = sets.union((set<map.entry<k, v>>)map.entryset(), unionset); } return unionset; 

but fails compile, error:

cannot cast set<map.entry<capture#27-of ? extends k, capture#28-of ? extends v>> set<map.entry<k,v>> 

i expected similar unsafe cast, seems forbidden in context, presumably due nested generics.

so 2 questions:

  1. why sort of cast forbidden, yet casts of top-level generic allowed?
  2. is there better way provide view union of these sets (with type set<map.entry<k, v>>)?

this technically doable unsafe raw cast

set<map.entry<k, v>> unionset = immutableset.of(); for(map<? extends k, ? extends v> map : chain) {   unionset = sets.union((set) map.entryset(), unionset); } 

...and best way provide live view of union of entry sets.

as far why casts of generic arguments aren't allowed, suspect there's technically no subtyping relationship between set<map.entry<? extends k, ? extends v>> , set<map.entry<k, v>>. might different verbose technically different set<? extends map.entry<? extends k, ? extends v>>, technically generalization of set<map.entry<k, v>> whereas other not.


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

firemonkey - How do I make a beep sound in Android using Delphi and the API? -

jdbc - Not able to establish database connection in eclipse -