java – 从Set中删除元素
发布时间:2020-05-25 15:40:54 所属栏目:Java 来源:互联网
导读:我正在尝试删除一组中长度均匀的所有字符串.到目前为止,这是我的代码,但是我无法从增强型for循环中的迭代器中获取索引. public static void removeEvenLength(SetString list) { for (String s : list) { if (s.length() % 2 == 0) { list.remo
|
我正在尝试删除一组中长度均匀的所有字符串.到目前为止,这是我的代码,但是我无法从增强型for循环中的迭代器中获取索引. public static void removeEvenLength(Set<String> list) {
for (String s : list) {
if (s.length() % 2 == 0) {
list.remove(s);
}
}
}
解决方法集合没有元素索引的概念.元素在集合中没有顺序.此外,迭代时应使用迭代器,以便在循环时从集合中删除元素时避免使用ConcurrentModificationException:
for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) {
String s = iterator.next();
if (s.length() % 2 == 0) {
iterator.remove();
}
}
请注意对Iterator.remove()的调用,而不是对Set.remove()的调用. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
