简体   繁体   English

如何检查一个元素是否已从 Map 中删除

[英]How to check if an element has been removed from a Map

How can I check that an element has been properly removed from a Map in java?如何检查某个元素是否已从Map中的 Map 中正确删除?

Given:鉴于:

ConcurrentHashMap<Integer,Object> myMap = new ConcurrentHashMap<>();
myMap.put(1, new Object());

myMap.remove(1);

Is the below code the only way to check it?下面的代码是检查它的唯一方法吗?

myMap.contains(1);

remove() returns the removed object, or null if it is not present in the map:如果 map 中不存在, remove()返回已删除的 object 或null

Returns:回报:
the previous value associated with key, or null if there was no mapping for key.与键关联的先前值,如果没有键映射,则为 null。

Object removedObject = myMap.remove(1);
boolean wasRemoved = removedObject != null;

In fact by using, contains() , the object might have been removed by another thread between the calls to remove() and contains() , if the map is shared between threads.事实上,通过使用contains() () ,如果 map 在线程之间共享,则 object 可能已在调用remove()contains()之间被另一个线程删除。 That your question uses a ConcurrentHashMap hints that concurrency might be a case here.您的问题使用ConcurrentHashMap暗示并发可能是这里的情况。

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

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