如何从同步映射java向同步/非同步映射添加映射项
如何使用addAll()-Java从同步映射向同步/非同步映射添加映射项如何从同步映射java向同步/非同步映射添加映射项,java,collections,map,Java,Collections,Map,如何使用addAll()-Java从同步映射向同步/非同步映射添加映射项 maph=Collections.synchronizedMap(新的HashMap()); Map g=Collections.synchronizedMap(新的HashMap()); //或者更好-Map=newhashmap(); h、 出售(“kkk”、“eee”); Set s=h.entrySet(); Set ss=g.entrySet(); ss.addAll(s)//导致两个同步版本的Unsupport
maph=Collections.synchronizedMap(新的HashMap());
Map g=Collections.synchronizedMap(新的HashMap());
//或者更好-Map=newhashmap();
h、 出售(“kkk”、“eee”);
Set s=h.entrySet();
Set ss=g.entrySet();
ss.addAll(s)//导致两个同步版本的UnsupportdOperationException
//映射g和未同步的,即使放置此操作
//在同步块中(同步(h){},和同步(g){})
HashMap
的EntrySet
不支持addAll
、句号。同步与此无关。要将所有内容从h复制到g,只需执行g.putAll(h)代码>
为Map指定equals()
的方式。条目
意味着add
和addAll
操作对于入口集将无法正常运行。条目表示,如果两个条目的键和值都匹配,则这两个条目是相等的。因此,您应该能够将[“Foo”,“Baz”]添加到已经包含[“Foo”,“Bar”]的入口集中,因为根据equals
,它们不相同。当然,我们知道这是不可能的,entrySet不能同时包含这两个元素,Foo的新映射必须替换旧映射。因此,这些方法根本不受支持
Map<String,String> h = Collections.synchronizedMap(new HashMap<String,String>());
Map<String,String> g = Collections.synchronizedMap(new HashMap<String,String>());
// or even better - Map<String,String> = new HashMap<String,String>();
h.put("kkk","eee");
Set<Map.Entry<String,String>> s = h.entrySet();
Set<Map.Entry<String,String>> ss = g.entrySet();
ss.addAll(s); //causes unsupportedoperationexception for both the synchronized version
// of map g and the unsynchronized, even if this operation is placed
// in a synchronized block (synchronized(h){}, and synchronized(g){})