ArrayList 删除元素问题总结

	/**
	 * List每remove掉一个元素,后面的元素都会向前移动,此时如果执行i=i+1,则刚刚移过来的元素没有被读取。
	 * 
	 * @author zw
	 * @date  2013-4-15
	 * @return void
	 */
	@Test
	public void testRemove(){
		List<String> al = new ArrayList<String>(5);
		al.add("not1");
		al.add("not2");
		al.add("not3");
		al.add("not4");
		al.add("not5");
		List<String> al2 = new ArrayList<String>();
		List<String> al3 = new ArrayList<String>();
		List<String> al4 = new ArrayList<String>();
		al2.addAll(al);
		al3.addAll(al);
		al4.addAll(al);
		
		 //错误,不能全部remove
		System.out.println("begin al size: "+al.size());
		for(int i=0;i<al.size();i++){   
			String str=al.get(i);
			if(str.indexOf("not")!=-1){
				al.remove(i);
			}
		}
		
		System.out.println("end al size: "+al.size());
		Assert.assertFalse(0==al.size());
		
		//方法1:正确,可以全部remove
	
		System.out.println("begin al2 size: "+al2.size());
		Iterator<String> iterator=al2.iterator();
		while(iterator.hasNext()){
			String str=iterator.next();
			if(str.indexOf("not")!=-1){
				iterator.remove();
			}
		}
		System.out.println("end al2 size: "+al2.size());
		Assert.assertEquals(0, al2.size());
		
		//方法2:倒过来遍历,ok
		System.out.println("begin al3 size: "+al3.size());
		for(int i=al3.size()-1;i>=0;i--){   
			String str=al3.get(i);
			if(str.indexOf("not")!=-1){
				al3.remove(i);
			}
		}
		
		System.out.println("end al3 size: "+al3.size());
		Assert.assertEquals(0, al3.size());
		
		//方法3:每移除一个元素以后再把i移回来
		System.out.println("begin al4 size: "+al4.size());
		for(int i=0;i<al4.size();i++){   
			String str=al4.get(i);
			if(str.indexOf("not")!=-1){
				al4.remove(i);
				i=i-1;
			}
		}
		
		System.out.println("end al4 size: "+al4.size());
		Assert.assertEquals(0, al4.size());
		
	}

 

你可能感兴趣的:(ArrayList)