例如,我有这样的代码:
public void addDocument(DocumentId documentId, Reader reader) throws IOException {
String s = "";
List<String> list;
BufferedReader br = new BufferedReader(reader);
while((s=br.readLine())!=null)
{
list = Arrays.asList(s.toLowerCase().split("\\W+"));
for(int i = 0; i < list.size(); i++)
{
if(!map.containsKey(list.get(i)))
{
Set<DocumentId> newset = new HashSet<>();
newset.add(documentId);
map.put(list.get(i), newset);
}
else
{
Set<DocumentId> set = map.get(list.get(i));
set.add(documentId);
map.put(list.get(i), set);
}
}
}
}
是map.put(list.get(i), set);
在映射中创建键和值的副本?如果是这样,我应该在再次添加更新的列表之前删除该对吗?
附注 map 是Map<String, Set<DocumentId>>
最佳答案
Map
不允许重复key,Map
内部的key会替换旧值,可以查看API here :
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
关于java - 当您更新一个集合(即映射中的值),然后将键和值放入映射中时,是否会创建重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43057216/