java學習過程的簡單記錄
阿新 • • 發佈:2018-10-17
pub list 9.png tar 學習過程 object stat 鏈表 java
1、LinkedList與ArrayList的區別
1)、LinkedList是基於鏈表的數據結構,ArrayList是實現了基於動態數組的數據結構;
2)、對於查詢(get),ArrayList比LinkedList效率高,因為LinkedList要移動指針
對於新增(insert)和刪除(remove),LinkedList比ArrayList效率高,因為ArrayList要移動數據
代碼如下:
public class ComporeTest {
private static Logger logger = LoggerFactory.getLogger(ComporeTest.class);
private static Integer N = 5000;
public static Long timeList(List list){
Long start = System.currentTimeMillis();
logger.info("start{}",start);
for(int i = 0; i < N; i++){
list.add(i);
}
logger.info("timeList{}",System.currentTimeMillis() - start);
return System.currentTimeMillis() - start;
}
public static List addList(List list){
Object o = new Object();
for(int i = 0;i < N; i++){
list.add(0,o);
}
logger.info("測試ArrayList與LinkedList的效率");
return list;
}
static Long readList(List list){
long start = System.currentTimeMillis();
for(int i = 0; i < list.size(); i++){
list.get(i);
}
return System.currentTimeMillis() - start ;
}
public static void main(String [] args){
logger.info("ArrayList添加"+N+"條消耗時間:{}",timeList(new ArrayList()));
logger.info("LinkedList添加"+N+"條消耗時間:{}",timeList(new LinkedList()));
List arrayList = addList(new ArrayList<>()) ;
List linkedList = addList(new LinkedList<>());
logger.info("ArrayList查詢"+N+"消耗時間:{}",readList(arrayList));
logger.info("LinkedList查詢"+N+"消耗時間:{}",readList(linkedList));
}
}
測試結果:
java學習過程的簡單記錄