HashMap 优化:使用迭代器移除元素
HashMap\u003CString, MyInfoWindow\u003E infoWindowMap \u003d new HashMap\u003C\u003E();\n\nMyInfoWindow infoWindow \u003d infoWindowMap.get(bean1.getId());\n if (infoWindow \u003d\u003d null) {\n infoWindow \u003d new MyInfoWindow(mapView, bean1.getName(), description, bean1.getId());\n infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(), bean1.getLongitude()), 0, -30);\n infoWindowMap.put(bean1.getId(), infoWindow);\n infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(),bean1.getLongitude()), 0, -30);\n\n } else {\n infoWindow.update(new GeoPoint(bean1.getLatitude(),bean1.getLongitude()), bean1.getName(), bean1.getCaluesdata());\n }\n\n for ( int i\u003d 0;i\u003CcustomBeans.size();i++){\n if (infoWindowMap.get(bean.getData().getTargetId())!= null){\n infoWindowMap.get(bean.getData().getTargetId()).close();\n infoWindowMap.get(bean.getData().getTargetId()).onDetach();\n infoWindowMap.remove( infoWindowMap.get(bean.getData().getTargetId()));\n \n } \n}infoWindowMap 对应的对象移除 ,其中hashMap 中的String 好像未移除干净。 优化内容:要优化代码,可以改为使用迭代器来遍历并移除HashMap中的元素。以下是修改后的代码:\n\njava\nHashMap\u003CString, MyInfoWindow\u003E infoWindowMap \u003d new HashMap\u003C\u003E();\n\nMyInfoWindow infoWindow \u003d infoWindowMap.get(bean1.getId());\nif (infoWindow \u003d\u003d null) {\n infoWindow \u003d new MyInfoWindow(mapView, bean1.getName(), description, bean1.getId());\n infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(), bean1.getLongitude()), 0, -30);\n infoWindowMap.put(bean1.getId(), infoWindow);\n infoWindow.open(getContext(), new GeoPoint(bean1.getLatitude(),bean1.getLongitude()), 0, -30);\n\n} else {\n infoWindow.update(new GeoPoint(bean1.getLatitude(),bean1.getLongitude()), bean1.getName(), bean1.getCaluesdata());\n}\n\nIterator\u003CMap.Entry\u003CString, MyInfoWindow\u003E\u003E iterator \u003d infoWindowMap.entrySet().iterator();\nwhile (iterator.hasNext()) {\n Map.Entry\u003CString, MyInfoWindow\u003E entry \u003d iterator.next();\n if (entry.getKey().equals(bean.getData().getTargetId())) {\n MyInfoWindow targetInfoWindow \u003d entry.getValue();\n targetInfoWindow.close();\n targetInfoWindow.onDetach();\n iterator.remove(); // 使用迭代器的remove方法移除元素\n }\n}\n\n\n通过使用迭代器的remove方法,可以在循环中安全地移除HashMap中的元素,并确保String对象被完全移除。
原文地址: https://www.cveoy.top/t/topic/pq5N 著作权归作者所有。请勿转载和采集!