查找一個對象:
i = Collections.binarySearch(c, element);
i = Collections.binarySearch(c, element, comparator);
但是這些list必須是已經排好序了。而且要注意的是這個算法需要隨機訪問collection,如果不支持隨機訪問那么這個算法的效率可能會很低。
幾種常用Collection:
ArrayList
An indexed sequence that grows and shrinks dynamically
可以隨機訪問,但是如果要從中間刪除一個對象會影響效率,因為有些未刪除的對象要相應的調整位置。非線程安全,但效率會比Vector要高,如果在單線程下,選它而不是Vector。
LinkedList
An ordered sequence that allows efficient insertions and removal at any location
只能按順序訪問,添加刪除很方便。雖然提供了get(n)方法,但實際上還是順序訪問的,如果發現在LinkedList里面使用了這個方法,要考慮這個List類型是否選的合適
HashSet
An unordered collection that rejects duplicates
以hashcode為索引,適用于不知道所存對象位置而想尋找某個對象的情況。不可重復
TreeSet
A sorted set
與HashSet類似,但是所存對象是排了序的
LinkedHashSet
A set that remembers the order in which elements were inserted
PriorityQueue
A collection that allows efficient removal of the smallest element
加入Queue的時候會給與一個優先級,從queue中取出的時候先取出優先級最低的
HashMap
A data structure that stores key/value associations
存儲key/value對,非線程安全,與HashTable相比效率要高些
treeMap
A map in which the keys are sorted
排序的HashMap
LinkedHashMap
A map that remembers the order in which entries were added
文章來源于領測軟件測試網 http://www.kjueaiud.com/