要优化代码,可以改为使用迭代器来遍历并移除HashMap中的元素。以下是修改后的代码:

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

MyInfoWindow infoWindow = infoWindowMap.get(bean1.getId());
if (infoWindow == null) {
    infoWindow = new MyInfoWindow(mapView, bean1.getName(), description, bean1.getId());
    infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(), bean1.getLongitude()), 0, -30);
    infoWindowMap.put(bean1.getId(), infoWindow);
    infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(),bean1.getLongitude()), 0, -30);

} else {
    infoWindow.update(new GeoPoint(bean1.getLatitude(),bean1.getLongitude()),  bean1.getName(), bean1.getCaluesdata());
}

Iterator<Map.Entry<String, MyInfoWindow>> iterator = infoWindowMap.entrySet().iterator();
while (iterator.hasNext()) {
    Map.Entry<String, MyInfoWindow> entry = iterator.next();
    if (entry.getKey().equals(bean.getData().getTargetId())) {
        MyInfoWindow targetInfoWindow = entry.getValue();
        targetInfoWindow.close();
        targetInfoWindow.onDetach();
        iterator.remove(); // 使用迭代器的remove方法移除元素
    }
}

通过使用迭代器的remove方法,可以在循环中安全地移除HashMap中的元素,并确保String对象被完全移除

HashMapString MyInfoWindow infoWindowMap = new HashMap; MyInfoWindow infoWindow = infoWindowMapgetbean1getId; if infoWindow == null infoWindow = new MyInfoWindowma

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

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