文章目录
一、集合
二 、List集合
ArrayList集合的特点:
Vector集合的特点:
LinkedList集合的特点
三、Set 集合
HashSet集合的特点
TreeSet
LinkedHashSet
Queue
四、Map集合
1.HashMap集合的特点
Hashtable集合的特点
TreeMap集合的特点
一、集合
集合总主要是三种:List,Set,Queue
- Collection:是集合List,Set,Queue的基本的接口。
- Iterator:迭代器,提供方法访问集合中的数据。
- Map :是映射表的基础接口。
二 、List集合
ArrayList集合的特点:
- 排列有序,可重复
ArrayList<String> list = new ArrayList<>();
list.add("b");
list.add("a");
list.add("a");
System.out.println(list.get(0));
System.out.println(list.get(1));
System.out.println(list.get(2))
- 底层使用数组
private static final Object[] EMPTY_ELEMENTDATA = {};
/**
* Shared empty array instance used for default sized empty instances. We
* distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
* first element is added.
*/
private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
/**
* The array buffer into which the elements of the ArrayList are stored.
* The capacity of the ArrayList is the length of this array buffer. Any
* empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
* will be expanded to DEFAULT_CAPACITY when the first element is added.
*/
transient Object[] elementData; // non-private to simplify nested class access
- 速度快,增删慢
- 线程不安全
- 容量不够,ArrayList是当前容量*1.5+1
- private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + (oldCapacity >> 1);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// minCapacity is usually close to size, so this is a win:
elementData = Arrays.copyOf(elementData, newCapacity);
}
Vector集合的特点:
- 排列有序,可重复
- 底层使用数组
- 速度快,增删慢
- 线程安全,效率低
- 容量不够,默认扩展一倍容量
private void grow(int minCapacity) {
// overflow-conscious code
int oldCapacity = elementData.length;
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
elementData = Arrays.copyOf(elementData, newCapacity);
}
LinkedList集合的特点
- 排列有序,可重复
- 底层使用双向循环表数据结构。
- 查询速度慢,增加和删除快
- 线程不安全。
三、Set 集合
HashSet集合的特点
- 排列无序,不可重复
- 底层使用hash表实现
- 存取速度快
- 内部是HashMap
TreeSet
- 排列无序,不可重复
- 底层使用二叉树实现
- 排序存储
- 内部是TreeMap和sortedSet
LinkedHashSet
- 采用hash表存储,并用双向链表记录插入顺序。
- 内部是LinkedHashMap。
Queue
在两端出入的List,可以使用数组和链表实现。
四、Map集合
1.HashMap集合的特点
键不可重复,值可以重复。
底层哈希表
线程不安全
允许key值为null,value也可以为空。
capacity:当前数组容量,始终保持 2^n,可以扩容,扩容后数组大小为当前的 2 倍。
loadFactor:负载因子,默认为 0.75。
threshold:扩容的阈值,等于 capacity * loadFactor
Hashtable集合的特点
- 键不可重复,值可重复
- 底层哈希表
- 线程安全
- key value都不允许为空
TreeMap集合的特点
- 键不可重复,值可重复
- 底层二叉树。