前言
本文档对java 集合的相关类和接口及其关系进行简单介绍。
1 Collection
Collection是集合的顶层接口,其相关类和接口的关系如下图所示。
Collection: A collection represents a group of objects, known as its elements. Some collections allow duplicate elements and others do not. Some are ordered and others unordered.
List:An ordered collection.
Set:A collection that contains no duplicate elements.
Queue:A collection designed for holding elements prior to processing. Queues typically, but do not necessarily, order elements in a FIFO (first-in-first-out) manner.
2 List
Deque:A linear collection that supports element insertion and removal at both ends. Deques can also be used as LIFO (Last-In-First-Out) stacks.
ArrayList:Resizable-array implementation of the List interface. Note that this implementation is not synchronized.
集合的元素存储在一个数组中,可以指定数组的大小,如果不指定,则数组的初始大小是10,当数组不够用时,数组长度会自动扩大2倍。
LinkedList:Doubly-linked list implementation of the List and Deque interfaces. Note that this implementation is not synchronized.
Vector:thread-safe
Stack:The Stack class represents a last-in-first-out (LIFO) stack of objects.
thread-safe
3 Set
HashSet:This class implements the Set interface, backed by a hash table (actually a HashMap instance). It makes no guarantees as to the iteration order of the set。
This class offers constant time performance for the basic operations (<tt>add</tt>, <tt>remove</tt>, <tt>contains</tt> and <tt>size</tt>), assuming the hash function disperses the elements properly among the buckets.
Note that this implementation is not synchronized.
TreeSet:A NavigableSet implementation based on a TreeMap.
The elements are ordered using their {@linkplain Comparable natural ordering}, or by a {@link Comparator} provided at set creation time, depending on which constructor is used.
Note that this implementation is not synchronized.
This implementation provides guaranteed log(n) time cost for the basic operations ({@code add}, {@code remove} and {@code contains}).
4 Map
TreeMap:A Red-Black tree based {@link NavigableMap} implementation.
This implementation provides guaranteed log(n) time cost for the{@code containsKey}, {@code get}, {@code put} and {@code remove} operations.
Note that this implementation is not synchronized.
存储的Key需要实现Comparable接口,或者在TreeMap初始化的时候指定Comparator的实现。
HashMap:Hash table based implementation of the Map interface.
This implementation provides constant-time performance for the basic operations (<tt>get</tt> and <tt>put</tt>), assuming the hash function disperses the elements properly among the buckets.
与HashTable类似,唯一的区别是HashTable是thread-safe,HashMap不是。
散列表用链表数组实现,每个列表叫做一个bucket。
存储的Key需要实现hashCode()方法,同时也要注意与equals()兼容。