一、概念:

一般我們都知道ArrayList* 由一個數組后推得到的 List。作為一個常規用途的對象容器使用,用于替換原先的 Vector。允許我們快速訪問元素,但在從列表中部插入和刪除元素時,速度卻嫌稍慢。一般只應該用ListIterator 對一個 ArrayList 進行向前和向后遍歷,不要用它刪除和插入元素;與 LinkedList 相比,它的效率要低許多LinkedList 提供優化的順序訪問性能,同時可以高效率地在列表中部進行插入和刪除操作。但在進行隨機訪問時,速度卻相當慢,此時應換用 ArrayList。
二、測試
本來自己寫了一些測試類想測試下ArrayList和LinkedList的性能比較,發現怎么寫都差強人意,今天在《Thinking in Java》中看到了這樣的一段代碼,個人覺得寫得不賴。
public class ListPerformance
{
private static final int REPS = 100;
private abstract static class Tester//內部抽象類,作為List測試。
{
String name;
int size;
Tester(String name, int size)
{
this.name = name;
this.size = size;
}
abstract void test(List a);
}
private static Tester[] tests = {new Tester("get", 300)//一個測試數組,存儲get(隨機取)、iteration(順序遍歷)、insert(中間插入)、remove(隨機刪除)
{
void test(List a)
{
for (int i = 0; i < REPS; i++) {
for (int j = 0; j < a.size(); j++) {
a.get(j);
}
}
}
}, new Tester("iteration", 300)
{
void test(List a)
{
for (int i = 0; i < REPS; i++) {
Iterator it = a.iterator();
while (it.hasNext()) it.next();
}
}
}, new Tester("insert", 1000)
{
void test(List a)
{
int half = a.size() / 2;
String s = "test";
ListIterator it = a.listIterator(half);
for (int i = 0; i < size * 10; i++) {
it.add(s);
}
}
}, new Tester("remove", 5000)
{
void test(List a)
{
ListIterator it = a.listIterator(3);
while (it.hasNext()) {
it.next();
it.remove();
}
}
},
};
public static void test(List a)
{
System.out.println("Testing " + a.getClass().getName());//輸出測試的類名稱
for (int i = 0; i < tests.length; i++) {
fill(a, tests[i].size);//填充空集合
System.out.print(tests[i].name);
long t1 = System.currentTimeMillis();
tests[i].test(a);//進行測試
long t2 = System.currentTimeMillis();
System.out.print(":" + (t2 - t1)+" ms ");
}
}
public static Collection fill(Collection c, int size)
{
for (int i = 0; i < size; i++) {
c.add(Integer.toString(i));
}
return c;
}
public static void main(String[] args)
{
test(new ArrayList());
System.out.println();
test(new LinkedList());
}
}
分享題目:深入淺析ArrayList和LinkedList的執行效率比較-創新互聯
URL分享:http://www.yijiale78.com/article48/dppohp.html
成都網站建設公司_創新互聯,為您提供品牌網站制作、App設計、網站營銷、App開發、網站排名、面包屑導航
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯