python与java删除列表的所有指定元素方法

在python里,我们知道直接用remove或者pop的for循环删除会出现问题,正确如下:


python:

a=[1,1,3,2]
while 1 in a:
    a.remove(1)
print(a)  #输出[3,2]

java:

同理,java用for删除也会出问题,正确方法是用迭代器:

List<Integer> n1=new ArrayList<Integer>();
        n1.add(1);
        n1.add(2);
        n1.add(30);
        n1.add(30);
        n1.add(30);
//        n1.remove(new Integer(30));   //此处注意remove删除整数的List默认是根据index,这样就是根据对象删除了
        
        Iterator<Integer> it=n1.iterator();
        while(it.hasNext()){
        	if(it.next().equals(30)){     //此处注意Integer的比较不要用==
        		it.remove();
        	}
        }
        for(int i = 0;i<n1.size();i++){
        	System.out.println(n1.get(i));
        }
	}


猜你喜欢

转载自blog.csdn.net/csdn_black/article/details/80407864
今日推荐