用什么ArrayList或LinkedList或TreeMap?

时间:2014-08-05 05:05:58

标签: java performance data-structures

在我的问题中,我有一大堆数字。在运行时,我想在这个排序的数字序列中插入一个数字,然后获取插入数字的下一个数字(升序接下来)(Everything is sorted),然后删除插入的数字。

还有一个约束,有时我想要插入的数字将与我的初始集合中的其他数字完全相同,在这种情况下我也想抓住下一个数字。

我很困惑我是否应该使用TreeMap(因为TreeMap总是排序,但带有一个键的开销)一个LinkedList(因为输入和删除值变得更容易)或一个简单的 数组列表?

我正在将这些数字加载到内存中并执行激烈的计算,我的平台是移动的,所以我想要一些有效的东西。任何提示?到目前为止,我使用链接列表,虽然我没有遇到任何性能问题,但我想加快这个过程。

2 个答案:

答案 0 :(得分:3)

如果我正确理解了您的问题,您实际上不必插入数字来获取下一个数字,无论如何您正在删除它。在这种情况下,你可以使用一个简单的ArrayList本身来做这样的事情以获得良好的性能

List<Integer> lst = new ArrayList<>();
lst.add(1);
lst.add(2);
lst.add(4);
lst.add(8);
lst.add(15);

// Collections.sort(lst); // assuming list is sorted

// your key 
int key = 7;

// binary search to look for position where it would be inserted.
// if negative number does not exist so next number would be at ' -pos - 1' 
// if positive number exists so next number would be at 'pos + 1' 
int pos = Collections.binarySearch(lst, key);
pos = pos < 0 ? -pos - 1 : pos + 1;

// check for out of bounds as search for last number would give index out of bounds
pos = pos == lst.size() ? pos - 1 : pos;

// your next number
System.out.println(lst.get(pos));

答案 1 :(得分:1)

收集类的性能分析

Collection          Number of Elements
Class               5000   10000   20000

HashSet               10      20      20
LinkedHashSet          0      10      20
Vector               661    2714   10936
ArrayList            651    2694   10676
LinkedList           762    3305   28122
TreeMap             1021   10256   52719
HashMap             1712   12629   60050
IdentityHashMap      391    1532    7000
WeakHashMap         1572  failed  failed
Hashtable           3145   21261   89103

上述结果的结论: -

HashSet and LinkedHashSet maintained an almost constant performance level, while 
the number of elements doubled twice. They are perfectly designed for the search
operation.

Vector, ArrayList and LinkedList decreased their performance exponentially as the
number of elements doubles.

TreeMap, HashMap, IdentityHashMap and Hashtable decreased their performance 
exponentially as the number of elements doubles.

WeakHashMap is not reliable as mentioned in the JDK specification.

有关集合类性能的更多详细信息: -

  1. Search operation performance on Collection classes
  2. Big-O Complexities of Collection classes
  3. Bog-O Complexities of Searching, Sorting & different Data Structures