天天看點

讓星星⭐月亮告訴你,LinkedList和ArrayList(指定位置/頭尾增加删除)

注:本篇主要是代碼執行結果現象及概因的淺述,建議結合另一篇一起看,加深了解:LinkedList和ArrayList底層資料結構及方法源碼說明

⭐⭐⭐代碼執行結論🌙🌙🌙:

public class TestArrayList {
	private static final int index = 100000;
	static List<Integer> list = null;
	public static void main(String[] args) {
		//測試ArrayList和LinkedList的插入效率
		addElementInList(list, "ArrayList");
		addElementInList(list, "LinkedList");
		//測試ArrayList和LinkedList的查詢效率
		
	}
	
	private static void addElementInList(List<Integer> list, String type){
		if(type == "ArrayList"){
			list = new ArrayList();
			for(int i = 0; i < index; i++){
				list.add(i);
			}
		}
		if(type == "LinkedList"){
			list = new LinkedList();
			for(int i = 0; i < index; i++){
				list.add(i);
			}
		}
		long begin = System.currentTimeMillis();
//		int n = 20000;
		int n = index;
//		int n = 0;
		for(int i = 0; i < index; i++){
			if(type == "LinkedList"){
				list.add(n,i);
//				((LinkedList)list).addLast(i);
//				((LinkedList)list).addFirst(i);
			}else{
				list.add(n,i);
//				list.add(i);
			}
		}
		
		long end = System.currentTimeMillis();
		System.out.printf("在%s集合的索引為%d的位置插入%d條資料,總耗時為%d毫秒\n", type,n, index, end - begin);
		
		
		/*long begin2 = System.currentTimeMillis();
		for(int i = 0; i < index/6; i++){
			if(type == "LinkedList"){
				((LinkedList)list).remove(i);
//				((LinkedList)list).remove((Object)i);
//				((LinkedList)list).remove();
			}else{
				((ArrayList)list).remove(i);
//				((ArrayList)list).remove((Object)i);
			}
		}
		long end2 = System.currentTimeMillis();
		System.out.printf("在%s集合remove(index)%d條資料,總耗時為%d毫秒\n", type, index, end2 - begin2);*/
		
		long begin2 = System.currentTimeMillis();
		for(int i = 0; i < index; i++){
			if(type == "LinkedList"){
//				((LinkedList)list).remove(i);
				((LinkedList)list).remove((Object)i);
//				((LinkedList)list).remove();
			}else{
//				((ArrayList)list).remove(i);
				((ArrayList)list).remove((Object)i);
			}
		}
		long end2 = System.currentTimeMillis();
		System.out.printf("在%s集合remove(Object)%d條資料,總耗時為%d毫秒\n", type, index, end2 - begin2);
	}
	
}