初始化需要進行比較的集合,統一增加10萬個元素,獲取整個過程的執行時間。
1、List集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private static void testList() { List<Integer> list = new ArrayList<Integer>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { list.add(i); } long endTime = System.currentTimeMillis(); // 獲取結束時間 System.out.println( "List添加元素程序運行時間為:" + (endTime - startTime) + "ms" ); // 輸出程序運行時間 } |
程序輸出:
List添加10萬個元素程序運行時間為:8ms
2、Set集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private static void testSet() { Set<Integer> set = new HashSet<Integer>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { set.add(i); } long endTime = System.currentTimeMillis(); // 獲取結束時間 System.out.println( "Set添加10萬個元素程序運行時間為:" + (endTime - startTime) + "ms" ); // 輸出程序運行時間 } |
程序輸出:
Set添加10萬個元素程序運行時間為:17ms
3、LinkedList集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
private static void testLinkedList() { List<Integer> list = new LinkedList<Integer>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { list.add(i); } long endTime = System.currentTimeMillis(); // 獲取結束時間 // 輸出程序運行時間 System.out.println( "LinkedList添加10萬個元素程序運行時間為:" + (endTime - startTime) + "ms" ); } |
程序輸出:
LinkedList添加10萬個元素程序運行時間為:8ms
4、TreeSet集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
private static void testTreeSet() { Set<Integer> set = new TreeSet<Integer>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { set.add(i); } long endTime = System.currentTimeMillis(); // 獲取結束時間 // 輸出程序運行時間 System.out.println( "TreeSet添加10萬個元素程序運行時間為:" + (endTime - startTime) + "ms" ); } |
程序輸出:
TreeSet添加10萬個元素程序運行時間為:40ms
總結:在不考慮去重和排序的情況下,以上幾個常用集合的執行效率排序為:ArrayList >= LinkedList > HashSet > TreeSet
5、HashMap集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private static void testHashMap() { Map<Integer, Object> hashMap = new HashMap<Integer, Object>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { hashMap.put(i, "test" ); } long endTime = System.currentTimeMillis(); // 獲取結束時間 // 輸出程序運行時間 System.out.println( "HashMap添加10萬個元素程序運行時間為:" + (endTime - startTime) + "ms" ); } |
程序輸出:
HashMap添加10萬個元素程序運行時間為:17ms
6、TreeMap集合增加元素
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
private static void testTreeMap() { Map<Integer, Object> treeMap = new TreeMap<Integer, Object>(); long startTime = System.currentTimeMillis(); // 獲取開始時間 for ( int i = 0 ; i < 100000 ; i++) { treeMap.put(i, "test" ); } long endTime = System.currentTimeMillis(); // 獲取結束時間 // 輸出程序運行時間 System.out.println( "TreeMap添加10萬個元素程序運行時間為:" + (endTime - startTime) + "ms" ); } |
程序輸出:
TreeMap添加10萬個元素程序運行時間為:40ms
總結:在不考慮排序的情況下,HashMap的執行效率高于TreeMap:HashMap > TreeMap。
以上這篇淺談Java中幾個常用集合添加元素的效率就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。