HashMap 移除操作优化:避免重复查询和使用正确参数

在使用 HashMap 移除对象时,经常会遇到一些常见的错误,例如重复查询 HashMap 以及使用错误的参数进行移除。以下代码展示了常见的错误示例,并提供了相应的优化方案。

错误示例:

HashMap<String, MyInfoWindow> infoWindowMap = new HashMap<>();

if (infoWindowMap.get(bean.getData().getTargetId())!= null){
    infoWindowMap.get(bean.getData().getTargetId()).close();
    infoWindowMap.get(bean.getData().getTargetId()).onDetach();
    infoWindowMap.remove( infoWindowMap.get(bean.getData().getTargetId()));
    
}

优化方案:

  1. 避免重复查询 HashMap: 在上述代码中,infoWindowMap.get(bean.getData().getTargetId()) 被多次调用,这会导致多次访问和查询 HashMap,降低代码效率。为了避免这种情况,可以将查询结果存储在一个临时变量中,然后在后续操作中使用该变量。

  2. 使用正确的参数进行移除: 在移除操作中,应该使用 targetId 作为参数进行移除,而不是使用 infoWindowMap.get(bean.getData().getTargetId())。 这是因为 infoWindowMap.get(bean.getData().getTargetId()) 返回的是 MyInfoWindow 对象,而不是 targetId,使用该对象作为移除参数会导致移除操作失败。

优化后的代码:

String targetId = bean.getData().getTargetId();
MyInfoWindow infoWindow = infoWindowMap.get(targetId);
if (infoWindow != null) {
    infoWindow.close();
    infoWindow.onDetach();
    infoWindowMap.remove(targetId);
}

通过以上优化,可以确保 HashMap 移除操作正确执行,并且移除干净。同时,也可以提高代码效率,减少代码冗余。


原文地址: https://www.cveoy.top/t/topic/pq4R 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录