1、 遍历删除元素—-list/set
public static void main(String args[]) {
List<String>
list =
new ArrayList<String>();
Iterator<String> itrList =
list.iterator();
while ( itrList.hasNext()) {
if ( itrList.next().equals(
"111")
{
itrList.remove();
}
}
for ( String str :
list) {
if (str.equals(
"111") {
list.remove(str);
}
}
}
2、 遍历删除元素—–Map
public static
void main(
String args[]) {
Map<
String,
String> map=
new HashMap<
String,
String>();
Iterator<Map.Entry<
String,
String>> itrMap = map.entryset().iterator();
while ( itrMap .hasNext()) {
Map.Entry<
String,
String> e = itrMap.next();
if ( e.getKey().equals(
"111")
{
itrMap.remove();
}
}
for ( Map.Entry<
String,
String> e : map.entrySet() ) {
if (e.getKey().equals(
"111") {
map.remove(str);
}
}
}
参考: 1、 遍历Map 2、 遍历list/set
注意: HashSet存放元素是通过Hashcode确定元素位置的,如果在存入后,修改了参与计算Hashcode的字段的值,那么remove就会失败,对象将永远删除不了,造成内存泄漏