导航:首页 > 编程语言 > javalist循环删除元素

javalist循环删除元素

发布时间:2024-04-04 09:06:35

java List 遍历和删除 急

List可以用序号来遍历,但通常推荐使用iterator来遍历
Iterator itr = list.iterator();
while (itr.hasNext()) {
Object nextObj = itr.next();
}

如果要全部删除,用clear()方法是最简单的。
另外,Iterator也带有remove()方法,可以在遍历的时候,根据一定条件来进行删除。

示例:

import java.util.*;

public class Test {
public static void print(List<Integer> list) {
Iterator<Integer> itr = list.iterator();
while (itr.hasNext()) {
System.out.print(itr.next());
System.out.print(", ");
}
System.out.println();
}

public static void main(String[] args) {
List<Integer> s = new ArrayList<Integer>();
for (Integer i = 0; i < 10; i++) {
s.add(i);
}
print(s);

Iterator<Integer> itr = s.iterator();
while (itr.hasNext()) {
Integer i = itr.next();
if (i % 3 == 0) {
itr.remove();
}
}
print(s);
}
}

⑵ java遍历list 并删除相同值对象

用一个for循环遍历List时,不能删除其中的元素。

用Iterator操作即可。

还有 Pro类要重写一下 toString方法。这样System.out.println里才能打印出来。

import java.util.*;

public class ListTest {
public static void main(String[] args) {

List<Pro> list = new ArrayList();
Pro p1 = new Pro("1000","1000");
Pro p2 = new Pro("1001","1002");
Pro p3 = new Pro("1003","1004");
Pro p4 = new Pro("1005","1006");
list.add(p1);
list.add(p2);
list.add(p3);
list.add(p4);

for (Iterator<Pro> i = list.iterator(); i.hasNext();) {
Pro o = i.next();
if(o.getProid().equals(o.getProName())){
i.remove();
}
}
System.out.println(list);
}
}

class Pro{
private String proid;
private String proName;

public String getProid() {
return proid;
}
public void setProid(String proid) {
this.proid = proid;
}
public String getProName() {
return proName;
}
public void setProName(String proName) {
this.proName = proName;
}
public Pro(String proid, String proName) {
super();
this.proid = proid;
this.proName = proName;
}
public Pro() {
}

public String toString() {
return proid + ":" + proName;
}
}

⑶ java镐庝箞鍒犻櫎涓涓闆嗗悎涓镄勫厓绱

java涓闆嗗悎list鎻愪緵remove()鏂规硶鍒犻櫎闆嗗悎涓镄勫厓绱 锛屼笉杩囬泦钖埚拰鏁扮粍涓嶅悓锛屽傛灉鍒犻櫎闆嗗悎涓涓涓鍏幂礌锛屾ゅ厓绱犲悗闱㈢殑鍏幂礌涓嬫爣浼氩噺1 锛屾墍浠ュ傛灉鏄鍒犻櫎涓涓鎸囧畾鍏幂礌灏卞彲浠ョ洿鎺ュ垹闄list.remove(i)锛屽傛灉寰鐜鍒犻櫎鍏ㄩ儴鍏幂礌鍙浠ヤ竴鐩村垹闄や笅镙囦负1镄勫厓绱狅纴鍒犻櫎list.size()娆★绂鎴栬呬粠钖庡垹闄わ纴姣忔″垹闄ゅ氨鎶娄笅镙囧噺1锛

⑷ java 怎么删除List中的指定元素

主要有三种方法:

  1. 用一个List 记录要删除的数据,最后removeAll(List);

⑸ HashMap和List遍历方法总结及如何遍历删除

(一)List的遍历方法及如何实现遍历删除
我们造一个list出来,接下来用不同方法遍历删除,如下代码:
List<String> list= new ArrayList<String>();famous.add("zs");famous.add("ls");famous.add("ww");famous.add("dz");

1、for循环遍历list:
for(int i=0;i<list.size();i++){if(list.get(i).equals("ls"))list.remove(i);}

这是一种很常见的遍历方式,但是使用这种遍历删除元素会出现问题,原因在于删除某个元素后,list的大小发生了变化,而你的索引
也在变化,所以会导致你在遍历的时候漏掉某些元素。比如当你删除第一个元素后,继续根据索引访问第二个元素后,因为删除的原因,
后面的元素都往前移动了以为,所以实际访问的是第三个元素。因此,这种遍历方式可以用在读取元素,而不适合删除元素。
2、增强for循环:
for(String x:list){if(x.equals("ls"))list.remove(x);}

这也是一种很常见的遍历方式,但是使用这种遍历删除元素也会出现问题,运行时会报异常
其实增强for循环是java语法糖的一种体现,如果大家通过反编译得到字节码,那么上面这段代码的内部实现如下所示:

for(Iterator<String> it = list.iterator();it.hasNext();){String s = it.next();if(s.equals("madehua")){list.remove(s);}}

下面就解释为什么会报异常。分析Iterator的源代码,重点分析整个调用该过程中的
函数(hasNext和remove):

private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; -1 if no such int expectedModCount = modCount; public boolean hasNext() { return cursor != size; // size为集合中元素的个数 } public E next() { checkForComodification(); int i = cursor; if (i >= size) throw new NoSuchElementException(); Object[] elementData = ArrayList.this.elementData; if (i >= elementData.length) throw new (); cursor = i + 1; return (E) elementData[lastRet = i]; } /* 此方法并没被调用,只是调用List.remove方法 public void remove() { checkForComodification(); try { ArrayList.this.remove(lastRet); // size字段减1 cursor = lastRet; lastRet = -1; expectedModCount = modCount; } catch (IndexOutOfBoundsException ex) { throw new (); } } */ final void checkForComodification() { // 检查修改和当前版本号是否一致,不一致则抛出异常 if (modCount != expectedModCount) throw new (); } } // List.remove @Override public boolean remove(Object object) { Object[] a = array; int s = size; if (object != null) { for (int i = 0; i < s; i++) { if (object.equals(a[i])) { System.array(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; // 核心代码:修改了版本号。这样当checkForComodification的时候,modCount值就和expectedModCount不同 return true; } } } else { for (int i = 0; i < s; i++) { if (a[i] == null) { System.array(a, i + 1, a, i, --s - i); a[s] = null; // Prevent memory leak size = s; modCount++; return true; } } } return false; }

接下来梳理一下流程,这时候你就会发现这个异常是在next方法的checkForComodification中抛出的。抛出的原因是
modCount !=expectedModCount。这里的modCount是指这个list对象从呢我出来到现在被修改的次数,当调用list
的add或者remove方法的时候,这个modCount都会自动增减;iterator创建的时候modCount被复制给了
expectedModcount,但是调用list的add和remove方法的时候不会同时自动增减expectedModcount,这样就导致
两个count不相等,从而抛出异常。大家如果理解了上面的执行流程,以后碰到类似这种问题,比如如果删除的是倒数
第二个元素却不会碰到异常。就会知道为什么了。

3、iterator遍历删除:

Iterator<String> it = list.iterator();while(it.hasNext()){String x = it.next();if(x.equals("del")){it.remove();}}

这种方式是可以正常遍历和删除的。但是你可能看到上面代码感觉和增强for循环内部实现的代码差不多,其实差别就在于上面使用
一个使用list.remove(),一个使用it.remove()。

(二)HashMap的遍历删除及如何实现遍历删除
一样我们先造一个hashmap出来,如下:

private static HashMap<Integer, String> map = new HashMap<Integer, String>();; public static void main(String[] args) { for(int i = 0; i < 10; i++){ map.put(i, "value" + i); } }

1、第一种遍历删除:

for(Map.Entry<Integer, String> entry : map.entrySet()){Integer key = entry.getKey();if(key % 2 == 0){System.out.println("To delete key " + key);map.remove(key);System.out.println("The key " + + key + " was deleted");}

这种遍历删除依旧会报异常,
2、第二种遍历删除:
Set<Integer> keySet = map.keySet(); for(Integer key : keySet){ if(key % 2 == 0){ System.out.println("To delete key " + key); keySet.remove(key); System.out.println("The key " + + key + " was deleted"); } }

这种遍历删除依旧会报异常,
3、第三种遍历删除:
Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();while(it.hasNext()){Map.Entry<Integer, String> entry = it.next();Integer key = entry.getKey();if(key % 2 == 0){ System.out.println("To delete key " + key); it.remove(); System.out.println("The key " + + key + " was deleted");}}

这种遍历是OK的
分析上述原因,如果大家理解了List的遍历删除,那么感觉HashMap的遍历删除是不是有类似之处啊。下面就分析一下原因:
如果查询源代码以上的三种的删除方式都是通过调用HashMap.removeEntryForKey方法来实现删除key的操作。
在removeEntryForKey方法内知识一场了key modCount就会执行一次自增操作,此时modCount就与expectedModCOunt不一致了
,上面三种remove实现中,只有第三种iterator的remove方法在调用完removeEntryForKey方法后同步了expectedModCount值与
modCount相同,所以iterator方式不会抛出异常。最后希望大家遇到问题到查询源代码,它会给你最好的解释!

阅读全文

与javalist循环删除元素相关的资料

热点内容
白盘怎么解压 浏览:472
辰语程序员学习笔记 浏览:47
程序员被公司劝退 浏览:523
java三子棋 浏览:690
加密空间怎么强制进入 浏览:343
ug分割曲线命令 浏览:209
学码思程序员 浏览:609
自考云学习app为什么登不上 浏览:406
domcer服务器昼夜更替怎么搞 浏览:434
plc和单片机哪个好 浏览:535
帝国神话组建云服务器 浏览:827
邓散木pdf 浏览:199
方舟怎么直连服务器图片教程 浏览:563
假相pdf 浏览:336
找对象找程序员怎么找 浏览:976
怎么投诉苹果商店app 浏览:470
华为手机如何看有多少个app 浏览:734
btr如何管理别的服务器 浏览:410
spwm软件算法 浏览:184
70多岁单身程序员 浏览:221