简体   繁体   中英

Adding entries to LinkedList inside ConcurrentHashMap not working

I have a ConcurrentHashMap that contains a string as a key and LinkedList as a value. 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. 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. And from this code it seems key is always same so all the time it will overrite the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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