java - 当您更新一个集合(即映射中的值),然后将键和值放入映射中时,是否会创建重复项?

标签 java hashmap set hashset

例如,我有这样的代码:

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/

相关文章:

java - Hibernate saveOrUpdate 方法会删除 child 吗?

java - 从链接读取生成的 HTML 文件

java - 无法找到javac

Java 按值对 HashMap 进行排序

java - 编译报错ConcurrentModificationException,试图使用移除同名的方法

batch-file - 管道之后 "set -P"为什么不起作用?

function - julia lang - 如何将多个函数应用于一个值

java - Android - 无法在启动屏幕上播放歌曲

java - 为 Multimap 的一个特定实例覆盖 toString()?

linq - 为什么空集的总和为空?