黑马程序员技术交流社区
标题:
扩展习题:ArrayList去除集合中所有的指定元素
[打印本页]
作者:
Zrz_K
时间:
2015-12-23 23:38
标题:
扩展习题:ArrayList去除集合中所有的指定元素
/**
* 需求
* ArrayList去除集合中所有的指定元素。
* 注意事项
* 每种方法的注意事项见行注释。
*/
public static void main(String[] args) {
ArrayList<String> c = new ArrayList<>(); //创建集合对象
c.add("a");
c.add("d");
c.add("c");
c.add("a");
c.add("a");
c.add("b");
c.add("a");
c.add("c");
c.add("b");
removeRepeat_1 (c , "a"); //调用三种方法删除传入集合中的指定元素
//removeRepeat_2 (c , "a");
//removeRepeat_3 (c , "a");
//removeRepeat_4 (c , "a");
System.out.println(c);
}
//contains判断
private static void removeRepeat_1 (ArrayList<String> c,String s){
while (c.contains(s)){
c.remove(s);
}
}
//for遍历,注意移除元素后索引需要自减,否则会跳过一个元素
private static void removeRepeat_2(ArrayList<String> c, String s) {
for (int i = 0; i < c.size(); i++) {
if (c.get(i).equals(s)) {
c.remove(i--); //索引--,否则会跳过一个元素
}
}
}
//for倒序遍历,无需考虑索引的问题,不会有遗漏
private static void removeRepeat_3(ArrayList<String> c, String s) {
for (int i = c.size() - 1; i >= 0; i--) {
if (c.get(i).equals(s)) {
c.remove(i);
}
}
}
//迭代器遍历,需要用迭代器自己的删除操作,否则会报并发修改异常
private static void removeRepeat_4(ArrayList<String> c, String s) {
Iterator it = c.iterator();
while (it.hasNext()) {
String ss = (String) it.next();
if (ss.equals(s)) {
it.remove(); //调用迭代器自身的删除方法
}
}
}
复制代码
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2