简体   繁体   English

在ConcurrentHashMap内部将条目添加到LinkedList无效

[英]Adding entries to LinkedList inside ConcurrentHashMap not working

I have a ConcurrentHashMap that contains a string as a key and LinkedList as a value. 我有一个ConcurrentHashMap,其中包含一个字符串作为键,而LinkedList作为一个值。 The size of the list should not be more than 5. I am trying to add some elements to the list but when I print out the Map I see only the last added element. 列表的大小不应超过5。我正在尝试向列表中添加一些元素,但是当我打印出地图时,我只会看到最后添加的元素。 Here is my code: 这是我的代码:

private ConcurrentHashMap<String, LinkedList<Date>> userDisconnectLogs = new ConcurrentHashMap<String, LinkedList<Date>>();

public void addNewDateEntry(String userId, LinkedList<Date> timeStamps) {
    if (timeStamps.size() >= 5) {
        timeStamps.poll();
        timeStamps.add(new Date());
        userDisconnectLogs.put(userId, timeStamps);
    } else {
        timeStamps.add(new Date());
        userDisconnectLogs.put(userId, timeStamps);
    }

    for (Entry<String, LinkedList<Date>> entry : userDisconnectLogs
            .entrySet()) {
        String key = entry.getKey().toString();
        ;
        LinkedList<Date> value = entry.getValue();
        System.out.println("key: " + key + " value: " + value.size());
    }
}

Thank you! 谢谢!

Here for hashMap key must be unique. 对于hashMap,此处的键必须唯一。 And from this code it seems key is always same so all the time it will overrite the data. 从这段代码看来,密钥始终是相同的,因此始终会覆盖数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM