一、Collection
//一般讨论集合类无非就是。这里的两种数组类型更是如此// 1底层数据结构// 2增删改查方式// 3初始容量,扩容方式,扩容时机。// 4线程安全与否// 5是否允许空,是否允许重复,是否有序所以以后在回答的时候按照这个模板回答
集合:List、Set、Queue的最基本接口
实现类,注意上面注释显示都没有同步,如果需要进行同步处理,需要覆盖默认的方法

二、List
有序集合,用户可以通过索引访问节点,并在列表中搜索节点
2.1 ArrayList
- 数组实现,能够快速随机访问(就是通过下标直接访问)
- 从中间删除和插入比较慢,但是查询和修改快。
- 没有初始化容量默认:10
- 扩容1.5 ,最多到Integer.Max
- 可序列化(通过writeobject来序列化)、可扩容
- 线程不安全
- 拓展:trimToSize(将容量最小化 )
- 同步:直接使用Vector,或者用Collections.synchronizedList方法把你的ArrayList变成一个线程安全的List
内部字典排序,可以使用sort方法,重写排序。
// ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>(); ret.sort(new Comparator<ArrayList<Integer>>() { //从小到大 @Override public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) { //注意这里的负号 return -o1.toString().compareTo(o2.toString()); } });List<String> synchronizedList = Collections.synchronizedList(list); synchronizedList.add("aaa"); synchronizedList.add("bbb"); for (int i = 0; i < synchronizedList.size(); i++) { System.out.println(synchronizedList.get(i)); }2.2 LinkList
链表实现,能够快速插入和删除,但是访问需要遍历,较慢
- 默认尾部插入,可以头部插入
2.3 Vector
- 数组索引,自动增长,默认容量10,capacityIncrement增长情况为0,如果设置了capacityIncrement,每次就增加capacityIncrement的容量。
- 默认capacityIncrement为0,则每次增长翻倍。
- 能够快速随机访问
- 支持clone()方法,可以被克隆
- 大部分方法都使用了synchronized修饰符,所以他是线程安全集合类
- 底层数组不加transient,序列化时会全部复制
三、Set
无序集合,存入和去除的顺序不一定相同,(hashCode)值不能重复
3.1 HashSet
通过hashCode来取值,如果equals相等则放在同一列中。
- 内部是HashMap
添加、查询如下
//map就是hashMap里面的信息 public boolean add(E e) { return map.put(e, PRESENT)==null; } public boolean contains(Object o) { return map.containsKey(o); }一般默认是构造hashmap,还可以构造linkedmap
/** * Constructs a new, empty linked hash set. (This package private * constructor is only used by LinkedHashSet.) The backing * HashMap instance is a LinkedHashMap with the specified initial * capacity and the specified load factor. * * @param initialCapacity the initial capacity of the hash map * @param loadFactor the load factor of the hash map * @param dummy ignored (distinguishes this * constructor from other int, float constructor.) * @throws IllegalArgumentException if the initial capacity is less * than zero, or if the load factor is nonpositive */ HashSet(int initialCapacity, float loadFactor, boolean dummy) { map = new LinkedHashMap<>(initialCapacity, loadFactor); }3.2 LinkedHashSet
进出是有序的
底层是HashSet-> LinkedHashMap->(HashMap、LinkedList)
是HashSet的子类,而且调用的就是HashSet里面的东西,默认0.75的加载因子(在Map里面会说明)
基本就是对HashSet进行封装/** * Constructs a new, empty linked hash set with the default initial * capacity (16) and load factor (0.75). */ public LinkedHashSet() { super(16, .75f, true); } /** * Constructs a new, empty linked hash set with the specified initial * capacity and the default load factor (0.75). * * @param initialCapacity the initial capacity of the LinkedHashSet * @throws IllegalArgumentException if the initial capacity is less * than zero */ public LinkedHashSet(int initialCapacity) { super(initialCapacity, .75f, true); }3.3 TreeSet
底层调用TreeMap
public TreeSet() { this(new TreeMap<E,Object>()); } public TreeSet(Comparator<? super E> comparator) { this(new TreeMap<>(comparator)); }
四、Map
内部关系图

除了使用迭代器遍历,还可使用Map自带的Entry进行遍历。
Map<String,String> m= new HashMap<String,String>(16);
for(int i=0;i<10;i++)
{
m.put(String.valueOf(i),String.valueOf(i));
}
//返回一个无序列表m.entrySet()
//方法一
for (Map.Entry<String, String> entry : m.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
//lamada表达式
m.forEach((key ,value)->{
System.out.println(key+":"+value);
});
//iterator遍历
Iterator<String> iterator2 = hashSet.iterator();
while(iterator2.hasNext()) {
String entry = iterator2.next();
System.out.println("key:"+entry) ;
}
default void forEach(BiConsumer<? super K, ? super V> action) {
Objects.requireNonNull(action);
for (Map.Entry<K, V> entry : entrySet()) {
K k;
V v;
try {
k = entry.getKey();
v = entry.getValue();
} catch(IllegalStateException ise) {
// this usually means the entry is no longer in the map.
throw new ConcurrentModificationException(ise);
}
action.accept(k, v);
}
}
4.1 HashMap
并没有实现Collection接口。
实现:数组+链表+红黑树
而负载因子表示一个散列表的空间的使用程度,有这样一个公式:initailCapacityloadFactor=HashMap的容量。
所以负载因子越大则散列表的装填程度越高,也就是能容纳更多的元素,元素多了,链表大了,所以此时索引效率就会降低。
反之,负载因子越小则链表中的数据量就越稀疏,此时会对空间造成烂费,但是此时索引效率高。
*注意 hashtable的数组的默认长度是11
- 非线程安全
- 只允许一个键记录为空
```java
public class HashMap
extends AbstractMap implements Map , Cloneable, Serializable {
/** 默认初始容量
* The default initial capacity - MUST be a power of two.
*/
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4; // aka 16
/**
* The maximum capacity, used if a higher value is implicitly specified
* by either of the constructors with arguments.
* MUST be a power of two <= 1<<30.
*/
static final int MAXIMUM_CAPACITY = 1 << 30;
/** 默认负载因子
* The load factor used when none specified in constructor.
*/
static final float DEFAULT_LOAD_FACTOR = 0.75f;
/**
* The bin count threshold for using a tree rather than list for a
* bin. Bins are converted to trees when adding an element to a
* bin with at least this many nodes. The value must be greater
* than 2 and should be at least 8 to mesh with assumptions in
* tree removal about conversion back to plain bins upon
* shrinkage.
* 达到阈值后就会将链表转化为红黑树,提高查找效率
* 默认阈值*/
static final int TREEIFY_THRESHOLD = 8;
}
- **查找**: 首先根据key的hashCode 进行定位,如果hashCode 相同则转到链表里面(到达阈值则变成红黑树提高效率logN),小于的时候换原成链表
- **扩容:一般是2倍扩容**
```java
//插入代码
/**
* Implements Map.put and related methods
*
* @param hash hash for key
* @param key the key
* @param value the value to put
* @param onlyIfAbsent if true, don't change existing value
* @param evict if false, the table is in creation mode.
* @return previous value, or null if none
*/
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
调整大小: 不是很懂
/**
* Initializes or doubles table size. If null, allocates in
* accord with initial capacity target held in field threshold.
* Otherwise, because we are using power-of-two expansion, the
* elements from each bin must either stay at same index, or move
* with a power of two offset in the new table.
*
* @return the table
*/
final Node<K,V>[] resize() {
Node<K,V>[] oldTab = table;
int oldCap = (oldTab == null) ? 0 : oldTab.length;
int oldThr = threshold;
int newCap, newThr = 0;
if (oldCap > 0) {
if (oldCap >= MAXIMUM_CAPACITY) {
threshold = Integer.MAX_VALUE;
return oldTab;
}
else if ((newCap = oldCap << 1) < MAXIMUM_CAPACITY &&
oldCap >= DEFAULT_INITIAL_CAPACITY)
newThr = oldThr << 1; // double threshold
}
else if (oldThr > 0) // initial capacity was placed in threshold
newCap = oldThr;
else { // zero initial threshold signifies using defaults
newCap = DEFAULT_INITIAL_CAPACITY;
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
}
if (newThr == 0) {
float ft = (float)newCap * loadFactor;
newThr = (newCap < MAXIMUM_CAPACITY && ft < (float)MAXIMUM_CAPACITY ?
(int)ft : Integer.MAX_VALUE);
}
threshold = newThr;
@SuppressWarnings({"rawtypes","unchecked"})
Node<K,V>[] newTab = (Node<K,V>[])new Node[newCap];
table = newTab;
if (oldTab != null) {
for (int j = 0; j < oldCap; ++j) {
Node<K,V> e;
if ((e = oldTab[j]) != null) {
oldTab[j] = null;
if (e.next == null)
newTab[e.hash & (newCap - 1)] = e;
else if (e instanceof TreeNode)
((TreeNode<K,V>)e).split(this, newTab, j, oldCap);
else { // preserve order
Node<K,V> loHead = null, loTail = null;
Node<K,V> hiHead = null, hiTail = null;
Node<K,V> next;
do {
next = e.next;
if ((e.hash & oldCap) == 0) {
if (loTail == null)
loHead = e;
else
loTail.next = e;
loTail = e;
}
else {
if (hiTail == null)
hiHead = e;
else
hiTail.next = e;
hiTail = e;
}
} while ((e = next) != null);
if (loTail != null) {
loTail.next = null;
newTab[j] = loHead;
}
if (hiTail != null) {
hiTail.next = null;
newTab[j + oldCap] = hiHead;
}
}
}
}
}
return newTab;
}
面试问题:
为什么HashMap的默认大小是16:
1 减少hash碰撞
2 提高map查询效率
3 分配过小防止频繁扩容
4 分配过大浪费资源
为什么链表的长度为8是变成红黑树?为什么为6时又变成链表?
随机hashCode算法下所有bin中节点的分布频率会遵循泊松分布,我们可以看到,一个bin中链表长度达到8个元素的概率为0.00000006,几乎是不可能事件。
6缩小,是因为8扩容,如果也设置为8那么变成红黑树和链表需要不断变化。
因为hashMap内部由链表变成红黑树是从8个开始,因为容量必须是2的n次方,所以选择16作为默认容量。为什么红黑树的扩张是8,在源码注释里面发现随机哈希符合泊松分布,桶在超过8的概率很小,通过概率计算选择8作为阈值,同时8的时候红黑树的效率也高于链表。为什么红黑树的收缩成链表为什么是6,因为如果也设置为8,那么可能会导致频繁收缩和扩容,导致效率低下,
4.2 LinkedHashMap
- HashMap和LinkedList共同实现,通过维护双向链表,put元素时,不但要把它加入到HashMap中去,还要加入到双向链表中。访问顺序,put和get操作已存在的Entry时,都会把Entry移动到双向链表的表尾(其实是先删除再插入)
- 线程不安全
public class LinkedHashMap<K,V>
extends HashMap<K,V>
implements Map<K,V>
{
/**
* The iteration ordering method for this linked hash map: <tt>true</tt>
* for access-order, <tt>false</tt> for insertion-order.
* 这里是表示按照什么顺序排序,默认是按照插入顺序,另外一个是访问顺序,即使get过的再
* @serial
*/
final boolean accessOrder;
/**
* HashMap.Node subclass for normal LinkedHashMap entries.
*/
static class Entry<K,V> extends HashMap.Node<K,V> {
Entry<K,V> before, after;
Entry(int hash, K key, V value, Node<K,V> next) {
super(hash, key, value, next);
}
}
/**
* Constructs an empty insertion-ordered <tt>LinkedHashMap</tt> instance
* with the specified initial capacity and load factor.
*
* @param initialCapacity the initial capacity
* @param loadFactor the load factor
* @throws IllegalArgumentException if the initial capacity is negative
* or the load factor is nonpositive
*/
public LinkedHashMap(int initialCapacity, float loadFactor) {
//因为继承了Hashmap,所以初始化容量和负载因子和那个一样
super(initialCapacity, loadFactor);
accessOrder = false;
}
}

4.3 Hashtable
- 初始化容量11,负载因子0.75
- 线程安全
- 通过加synchronized变成线程安全
- Hashtable既不支持Null key也不支持Null value
- 扩容如下 ```java //扩容机制 int newCapacity = (oldCapacity << 1) + 1; //2*i +1
//集成了Dictionary
public class Hashtable
}
[ Hashtable和Hashmap的区别](https://blog.csdn.net/wangxing233/article/details/79452946)<br />Hashtable 是一个哈希表,该类继承自Dictionary类,实现了 Map 接口,HashMap是继承AbstractMap实现。<br />HashMap允许将 null 作为一个 entry 的 key 或者 value,而 Hashtable 不允许
<a name="BgKNm"></a>
## 4.4 ConcurrentHashMap
- 线程安全,并且使用分段锁,默认分16段(分段锁源码有介绍)
- JDK1.8以前 使用Segment数组和多个HashEntry数组组成,Segment数组的意义就是将一个大的table分割成多个小的table来进行加锁,也就是上面的提到的锁分离技术,而每一个Segment元素存储的是HashEntry数组+链表,这个和HashMap的数据存储结构一样 。
- JDK1.8 中使用**CAS**无锁算法与**synchronized**保证并发安全,支持并发扩容,数据结构变更为**数组+链表+红黑树**,提高性能,ConcurrentHashMap的初始化其实是一个空实现,并没有做任何事,这里后面会讲到,这也是和其他的集合类有区别的地方,初始化操作并不是在构造函数实现的。
- 注意并发扩容!
1.JDK1.8的实现降低锁的粒度,JDK1.7版本锁的粒度是基于Segment的,包含多个HashEntry,而JDK1.8锁的粒度就是HashEntry(首节点)<br />2.JDK1.8版本的数据结构变得更加简单,使得操作也更加清晰流畅,因为已经使用synchronized来进行同步,所以不需要分段锁的概念,也就不需要Segment这种数据结构了(为了兼容还是保留了),由于粒度的降低,实现的复杂度也增加了<br /> 3.JDK1.8使用红黑树来优化链表,基于长度很长的链表的遍历是一个很漫长的过程,而红黑树的遍历效率是很快的,代替一定阈值的链表,这样形成一个最佳拍档。<br />4.JDK1.8为什么使用内置锁**synchronized**来代替重入锁**ReentrantLock**,我觉得有以下几点<br /> 1.因为粒度降低了,在相对而言的低粒度加锁方式,**synchronized**并不比**ReentrantLock**差,在粗粒度加锁中 ReentrantLock可能通过Condition来控制各个低粒度的边界,更加的灵活,而在低粒度中,Condition的优 势就没有了<br /> 2.JVM的开发团队从来都没有放弃**synchronized**,而且基于JVM的synchronized优化空间更大,使用内嵌的 关键字比使用API更加自然<br /> 3.在大量的数据操作下,对于JVM的内存压力,基于API的ReentrantLock会开销更多的内存,虽然不是瓶 颈,但是也是一个选择依据 。
```java
public class ConcurrentHashMap<K,V> extends AbstractMap<K,V>
implements ConcurrentMap<K,V>, Serializable {
private static final long serialVersionUID = 7249069246763182397L;
//默认容量
private static final int DEFAULT_CAPACITY = 16;
//负载均衡
private static final float LOAD_FACTOR = 0.75f;
//阈值
static final int TREEIFY_THRESHOLD = 8;
}
4.5 TreeMap
- 内部完全由红黑树实现
```java
/**
- A Red-Black tree based {@link NavigableMap} implementation.
- The map is sorted according to the {@linkplain Comparable natural
- ordering} of its keys, or by a {@link Comparator} provided at map
- creation time, depending on which constructor is used. 基于红黑树的实现 */
public class TreeMap
* The comparator used to maintain order in this tree map, or
* null if it uses the natural ordering of its keys.
* 比较方法
* @serial
*/
private final Comparator<? super K> comparator;
}
<a name="IGTCS"></a>
# 五、Stack
栈,Stack继承Vector
- **线程安全**
- empty():测试堆栈是否为空。
- peek(): 查看堆栈顶部的对象,但不从堆栈中移除它。
- pop():移除堆栈顶部的对象,并作为此函数的值返回该对象。
- push(E item) 把项压入堆栈顶部。
- search(Object o) 返回对象在堆栈中的位置,以 1 为基数。
```java
class Stack<E> extends Vector<E> {
/**
* Creates an empty Stack.
*/
public Stack() {
}
....
}
六、集合排序
七、Queue
底层类情况

实现类:
- LinkedList<>()
显然是用链表实现的
线程不安全
关系图如下,实现了Dequeu,list等
- LinkedBlockingDeque
链表双端,阻塞,默认大小为Integer.Max,所以注意初始化
线程安全,内部有锁!
- PriorityQueue 优先队列,内部实现应该也是堆。
八、总结
8.1 线程安全
- vector:就比arraylist多了个同步化机制(线程安全),因为效率较低,现在已经不太建议使用。在web应用中,特别是前台页面,往往效率(页面响应速度)是优先考虑的。
- statck:堆栈类,先进后出
- hashtable:就比hashmap多了个线程安全( 基本弃用,使用下面这个)
- ConcurrentHashMap:内部使用分段锁,默认16段。
- enumeration:枚举,相当于迭代器
- LinkedBlockingDeque :阻塞队列,内部有锁。
