廣告

2015年1月27日 星期二

[java] better way to remove object in arraylist, 從arraylist 拿掉不需要的

如果想在一個迴圈裡面拿掉不須要的item,有兩個可以呼叫,
1.remove(int index)
2.remove(object o)


package test_fb_api;

import java.util.ArrayList;
import java.util.HashMap;



public class testArrayListRemove {

	public static void main(String[] args) {
		
		ArrayList bookShelfData_ReName = new ArrayList();
		bookShelfData_ReName.add("1");
		bookShelfData_ReName.add("2");
		bookShelfData_ReName.add("3");
		bookShelfData_ReName.add("5");
		bookShelfData_ReName.add("2");
		
		System.out.println("remove(int index)");
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			System.out.println("===============");
			System.out.println("before:"+bookShelfData_ReName);
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				bookShelfData_ReName.remove(i);
			}
			System.out.println("after:"+bookShelfData_ReName);
			
		}
		System.out.println("****************************");
		
		ArrayList bookShelfData_ReName2 = new ArrayList();
		bookShelfData_ReName2.add("1");
		bookShelfData_ReName2.add("2");
		bookShelfData_ReName2.add("3");
		bookShelfData_ReName2.add("5");
		bookShelfData_ReName2.add("2");
		
		System.out.println("remove(object)");
		System.out.println("===============");
		ArrayList forRemove = new ArrayList();
		for(int i = 0 ; i< bookShelfData_ReName.size() ; i++)
		{	
			if(bookShelfData_ReName.get(i).equals("2"))
			{
				forRemove.add(bookShelfData_ReName.get(i));
			}
			
		}
		for(int i = 0 ; i< forRemove.size() ; i++)
		{
			bookShelfData_ReName.remove(forRemove.get(i));
		}
		System.out.println("after:"+bookShelfData_ReName);
		
		//still O(n)
	}

}



結果:


沒有留言:

張貼留言