diff --git a/README.md b/README.md
index 39b43f30..2b4e688d 100644
--- a/README.md
+++ b/README.md
@@ -6,7 +6,7 @@
@@ -89,7 +89,7 @@ Leetcode 上数据库题目的解题记录。
> [Java 容器](https://github.com/CyC2018/InnterviewNotes/blob/master/notes/Java%20容器.md)
-源码分析:ArrayListVector、CopyOnWriteArrayList、LinkedList、HashMap、ConcurrentHashMap、LinkedHashMap、WeekHashMap。
+源码分析:ArrayList、Vector、CopyOnWriteArrayList、LinkedList、HashMap、ConcurrentHashMap、LinkedHashMap、WeekHashMap。
> [Java 并发](https://github.com/CyC2018/InnterviewNotes/blob/master/notes/Java%20并发.md)
diff --git a/notes/Java IO.md b/notes/Java IO.md
index 649f563a..93b1c46f 100644
--- a/notes/Java IO.md
+++ b/notes/Java IO.md
@@ -2,3 +2,572 @@
+<<<<<<< HEAD
+=======
+# 一、概览
+
+Java 的 I/O 大概可以分成以下几类:
+
+- 磁盘操作:File
+- 字节操作:InputStream 和 OutputStream
+- 字符操作:Reader 和 Writer
+- 对象操作:Serializable
+- 网络操作:Socket
+- 新的输入/输出:NIO
+
+# 二、磁盘操作
+
+File 类可以用于表示文件和目录的信息,但是它不表示文件的内容。
+
+递归地输出一个目录下所有文件:
+
+```java
+public static void listAllFiles(File dir) {
+ if (dir == null || !dir.exists()) {
+ return;
+ }
+ if (dir.isFile()) {
+ System.out.println(dir.getName());
+ return;
+ }
+ for (File file : dir.listFiles()) {
+ listAllFiles(file);
+ }
+}
+```
+
+# 三、字节操作
+
+使用字节流操作进行文件复制:
+
+```java
+public static void copyFile(String src, String dist) throws IOException {
+
+ FileInputStream in = new FileInputStream(src);
+ FileOutputStream out = new FileOutputStream(dist);
+ byte[] buffer = new byte[20 * 1024];
+
+ // read() 最多读取 buffer.length 个字节
+ // 返回的是实际读取的个数
+ // 返回 -1 的时候表示读到 eof,即文件尾
+ while (in.read(buffer, 0, buffer.length) != -1) {
+ out.write(buffer);
+ }
+
+ in.close();
+ out.close();
+}
+```
+
+
+
+Java I/O 使用了装饰者模式来实现。以 InputStream 为例,
+
+- InputStream 是抽象组件;
+- FileInputStream 是 InputStream 的子类,属于具体组件,提供了字节流的输入操作;
+- FilterInputStream 属于抽象装饰者,装饰者用于装饰组件,为组件提供额外的功能,例如 BufferedInputStream 为 FileInputStream 提供缓存的功能。
+
+实例化一个具有缓存功能的字节流对象时,只需要在 FileInputStream 对象上再套一层 BufferedInputStream 对象即可。
+
+```java
+FileInputStream fileInputStream = new FileInputStream(filePath);
+BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
+```
+
+DataInputStream 装饰者提供了对更多数据类型进行输入的操作,比如 int、double 等基本类型。
+
+# 四、字符操作
+
+不管是磁盘还是网络传输,最小的存储单元都是字节,而不是字符。但是在程序中操作的通常是字符形式的数据,因此需要提供对字符进行操作的方法。
+
+- InputStreamReader 实现从字节流解码成字符流;
+- OutputStreamWriter 实现字符流编码成为字节流。
+
+逐行输出文本文件的内容:
+
+```java
+public static void readFileContent(String filePath) throws IOException {
+ FileReader fileReader = new FileReader(filePath);
+ BufferedReader bufferedReader = new BufferedReader(fileReader);
+ String line;
+ while ((line = bufferedReader.readLine()) != null) {
+ System.out.println(line);
+ }
+ // 装饰者模式使得 BufferedReader 组合了一个 Reader 对象
+ // 在调用 BufferedReader 的 close() 方法时会去调用 fileReader 的 close() 方法
+ // 因此只要一个 close() 调用即可
+ bufferedReader.close();
+}
+```
+
+编码就是把字符转换为字节,而解码是把字节重新组合成字符。
+
+如果编码和解码过程使用不同的编码方式那么就出现了乱码。
+
+- GBK 编码中,中文字符占 2 个字节,英文字符占 1 个字节;
+- UTF-8 编码中,中文字符占 3 个字节,英文字符占 1 个字节;
+- UTF-16be 编码中,中文字符和英文字符都占 2 个字节。
+
+UTF-16be 中的 be 指的是 Big Endian,也就是大端。相应地也有 UTF-16le,le 指的是 Little Endian,也就是小端。
+
+Java 使用双字节编码 UTF-16be,这不是指 Java 只支持这一种编码方式,而是说 char 这种类型使用 UTF-16be 进行编码。char 类型占 16 位,也就是两个字节,Java 使用这种双字节编码是为了让一个中文或者一个英文都能使用一个 char 来存储。
+
+String 可以看成一个字符序列,可以指定一个编码方式将它编码为字节序列,也可以指定一个编码方式将一个字节序列解码为 String。
+
+```java
+String str1 = "中文";
+byte[] bytes = str1.getBytes("UTF-8");
+String str2 = new String(bytes, "UTF-8");
+System.out.println(str2);
+```
+
+在调用无参数 getBytes() 方法时,默认的编码方式不是 UTF-16be。双字节编码的好处是可以使用一个 char 存储中文和英文,而将 String 转为 bytes[] 字节数组就不再需要这个好处,因此也就不再需要双字节编码。getBytes() 的默认编码方式与平台有关,一般为 UTF-8。
+
+```java
+byte[] bytes = str1.getBytes();
+```
+
+# 五、对象操作
+
+序列化就是将一个对象转换成字节序列,方便存储和传输。
+
+- 序列化:ObjectOutputStream.writeObject()
+- 反序列化:ObjectInputStream.readObject()
+
+序列化的类需要实现 Serializable 接口,它只是一个标准,没有任何方法需要实现,但是如果不去实现它的话而进行序列化,会抛出异常。
+
+```java
+public static void main(String[] args) throws IOException, ClassNotFoundException {
+ A a1 = new A(123, "abc");
+ String objectFile = "file/a1";
+ ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(objectFile));
+ objectOutputStream.writeObject(a1);
+ objectOutputStream.close();
+
+ ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(objectFile));
+ A a2 = (A) objectInputStream.readObject();
+ objectInputStream.close();
+ System.out.println(a2);
+}
+
+private static class A implements Serializable {
+ private int x;
+ private String y;
+
+ A(int x, String y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ @Override
+ public String toString() {
+ return "x = " + x + " " + "y = " + y;
+ }
+}
+```
+
+不会对静态变量进行序列化,因为序列化只是保存对象的状态,静态变量属于类的状态。
+
+transient 关键字可以使一些属性不会被序列化。
+
+ArrayList 中存储数据的数组是用 transient 修饰的,因为这个数组是动态扩展的,并不是所有的空间都被使用,因此就不需要所有的内容都被序列化。通过重写序列化和反序列化方法,使得可以只序列化数组中有内容的那部分数据。
+
+```java
+private transient Object[] elementData;
+```
+
+# 六、网络操作
+
+Java 中的网络支持:
+
+- InetAddress:用于表示网络上的硬件资源,即 IP 地址;
+- URL:统一资源定位符;
+- Sockets:使用 TCP 协议实现网络通信;
+- Datagram:使用 UDP 协议实现网络通信。
+
+## InetAddress
+
+没有公有的构造函数,只能通过静态方法来创建实例。
+
+```java
+InetAddress.getByName(String host);
+InetAddress.getByAddress(byte[] address);
+```
+
+## URL
+
+可以直接从 URL 中读取字节流数据。
+
+```java
+public static void main(String[] args) throws IOException {
+
+ URL url = new URL("http://www.baidu.com");
+
+ /* 字节流 */
+ InputStream is = url.openStream();
+
+ /* 字符流 */
+ InputStreamReader isr = new InputStreamReader(is, "utf-8");
+
+ /* 提供缓存功能 */
+ BufferedReader br = new BufferedReader(isr);
+
+ String line;
+ while ((line = br.readLine()) != null) {
+ System.out.println(line);
+ }
+
+ br.close();
+}
+```
+
+## Sockets
+
+- ServerSocket:服务器端类
+- Socket:客户端类
+- 服务器和客户端通过 InputStream 和 OutputStream 进行输入输出。
+
+
+
+## Datagram
+
+- DatagramPacket:数据包类
+- DatagramSocket:通信类
+
+# 七、NIO
+
+- [Java NIO Tutorial](http://tutorials.jenkov.com/java-nio/index.html)
+- [Java NIO 浅析](https://tech.meituan.com/nio.html)
+- [IBM: NIO 入门](https://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html)
+
+新的输入/输出 (NIO) 库是在 JDK 1.4 中引入的,弥补了原来的 I/O 的不足,提供了高速的、面向块的 I/O。
+
+## 流与块
+
+I/O 与 NIO 最重要的区别是数据打包和传输的方式,I/O 以流的方式处理数据,而 NIO 以块的方式处理数据。
+
+面向流的 I/O 一次处理一个字节数据:一个输入流产生一个字节数据,一个输出流消费一个字节数据。为流式数据创建过滤器非常容易,链接几个过滤器,以便每个过滤器只负责复杂处理机制的一部分。不利的一面是,面向流的 I/O 通常相当慢。
+
+面向块的 I/O 一次处理一个数据块,按块处理数据比按流处理数据要快得多。但是面向块的 I/O 缺少一些面向流的 I/O 所具有的优雅性和简单性。
+
+I/O 包和 NIO 已经很好地集成了,java.io.\* 已经以 NIO 为基础重新实现了,所以现在它可以利用 NIO 的一些特性。例如,java.io.\* 包中的一些类包含以块的形式读写数据的方法,这使得即使在面向流的系统中,处理速度也会更快。
+
+## 通道与缓冲区
+
+### 1. 通道
+
+通道 Channel 是对原 I/O 包中的流的模拟,可以通过它读取和写入数据。
+
+通道与流的不同之处在于,流只能在一个方向上移动(一个流必须是 InputStream 或者 OutputStream 的子类),而通道是双向的,可以用于读、写或者同时用于读写。
+
+通道包括以下类型:
+
+- FileChannel:从文件中读写数据;
+- DatagramChannel:通过 UDP 读写网络中数据;
+- SocketChannel:通过 TCP 读写网络中数据;
+- ServerSocketChannel:可以监听新进来的 TCP 连接,对每一个新进来的连接都会创建一个 SocketChannel。
+
+### 2. 缓冲区
+
+发送给一个通道的所有数据都必须首先放到缓冲区中,同样地,从通道中读取的任何数据都要先读到缓冲区中。也就是说,不会直接对通道进行读写数据,而是要先经过缓冲区。
+
+缓冲区实质上是一个数组,但它不仅仅是一个数组。缓冲区提供了对数据的结构化访问,而且还可以跟踪系统的读/写进程。
+
+缓冲区包括以下类型:
+
+- ByteBuffer
+- CharBuffer
+- ShortBuffer
+- IntBuffer
+- LongBuffer
+- FloatBuffer
+- DoubleBuffer
+
+## 缓冲区状态变量
+
+- capacity:最大容量;
+- position:当前已经读写的字节数;
+- limit:还可以读写的字节数。
+
+状态变量的改变过程举例:
+
+① 新建一个大小为 8 个字节的缓冲区,此时 position 为 0,而 limit = capacity = 8。capacity 变量不会改变,下面的讨论会忽略它。
+
+
+
+② 从输入通道中读取 5 个字节数据写入缓冲区中,此时 position 移动设置为 5,limit 保持不变。
+
+
+
+③ 在将缓冲区的数据写到输出通道之前,需要先调用 flip() 方法,这个方法将 limit 设置为当前 position,并将 position 设置为 0。
+
+
+
+④ 从缓冲区中取 4 个字节到输出缓冲中,此时 position 设为 4。
+
+
+
+⑤ 最后需要调用 clear() 方法来清空缓冲区,此时 position 和 limit 都被设置为最初位置。
+
+
+
+## 文件 NIO 实例
+
+以下展示了使用 NIO 快速复制文件的实例:
+
+```java
+public static void fastCopy(String src, String dist) throws IOException {
+
+ /* 获得源文件的输入字节流 */
+ FileInputStream fin = new FileInputStream(src);
+
+ /* 获取输入字节流的文件通道 */
+ FileChannel fcin = fin.getChannel();
+
+ /* 获取目标文件的输出字节流 */
+ FileOutputStream fout = new FileOutputStream(dist);
+
+ /* 获取输出字节流的通道 */
+ FileChannel fcout = fout.getChannel();
+
+ /* 为缓冲区分配 1024 个字节 */
+ ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
+
+ while (true) {
+
+ /* 从输入通道中读取数据到缓冲区中 */
+ int r = fcin.read(buffer);
+
+ /* read() 返回 -1 表示 EOF */
+ if (r == -1) {
+ break;
+ }
+
+ /* 切换读写 */
+ buffer.flip();
+
+ /* 把缓冲区的内容写入输出文件中 */
+ fcout.write(buffer);
+
+ /* 清空缓冲区 */
+ buffer.clear();
+ }
+}
+```
+
+## 选择器
+
+NIO 常常被叫做非阻塞 IO,主要是因为 NIO 在网络通信中的非阻塞特性被广泛使用。
+
+NIO 实现了 IO 多路复用中的 Reactor 模型,一个线程 Thread 使用一个选择器 Selector 通过轮询的方式去监听多个通道 Channel 上的事件,从而让一个线程就可以处理多个事件。
+
+通过配置监听的通道 Channel 为非阻塞,那么当 Channel 上的 IO 事件还未到达时,就不会进入阻塞状态一直等待,而是继续轮询其它 Channel,找到 IO 事件已经到达的 Channel 执行。
+
+因为创建和切换线程的开销很大,因此使用一个线程来处理多个事件而不是一个线程处理一个事件具有更好的性能。
+
+应该注意的是,只有套接字 Channel 才能配置为非阻塞,而 FileChannel 不能,为 FileChannel 配置非阻塞也没有意义。
+
+
+
+### 1. 创建选择器
+
+```java
+Selector selector = Selector.open();
+```
+
+### 2. 将通道注册到选择器上
+
+```java
+ServerSocketChannel ssChannel = ServerSocketChannel.open();
+ssChannel.configureBlocking(false);
+ssChannel.register(selector, SelectionKey.OP_ACCEPT);
+```
+
+通道必须配置为非阻塞模式,否则使用选择器就没有任何意义了,因为如果通道在某个事件上被阻塞,那么服务器就不能响应其它事件,必须等待这个事件处理完毕才能去处理其它事件,显然这和选择器的作用背道而驰。
+
+在将通道注册到选择器上时,还需要指定要注册的具体事件,主要有以下几类:
+
+- SelectionKey.OP_CONNECT
+- SelectionKey.OP_ACCEPT
+- SelectionKey.OP_READ
+- SelectionKey.OP_WRITE
+
+它们在 SelectionKey 的定义如下:
+
+```java
+public static final int OP_READ = 1 << 0;
+public static final int OP_WRITE = 1 << 2;
+public static final int OP_CONNECT = 1 << 3;
+public static final int OP_ACCEPT = 1 << 4;
+```
+
+可以看出每个事件可以被当成一个位域,从而组成事件集整数。例如:
+
+```java
+int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
+```
+
+### 3. 监听事件
+
+```java
+int num = selector.select();
+```
+
+使用 select() 来监听到达的事件,它会一直阻塞直到有至少一个事件到达。
+
+### 4. 获取到达的事件
+
+```java
+Set keys = selector.selectedKeys();
+Iterator keyIterator = keys.iterator();
+while (keyIterator.hasNext()) {
+ SelectionKey key = keyIterator.next();
+ if (key.isAcceptable()) {
+ // ...
+ } else if (key.isReadable()) {
+ // ...
+ }
+ keyIterator.remove();
+}
+```
+
+### 5. 事件循环
+
+因为一次 select() 调用不能处理完所有的事件,并且服务器端有可能需要一直监听事件,因此服务器端处理事件的代码一般会放在一个死循环内。
+
+```java
+while (true) {
+ int num = selector.select();
+ Set keys = selector.selectedKeys();
+ Iterator keyIterator = keys.iterator();
+ while (keyIterator.hasNext()) {
+ SelectionKey key = keyIterator.next();
+ if (key.isAcceptable()) {
+ // ...
+ } else if (key.isReadable()) {
+ // ...
+ }
+ keyIterator.remove();
+ }
+}
+```
+
+## 套接字 NIO 实例
+
+```java
+public class NIOServer {
+
+ public static void main(String[] args) throws IOException {
+
+ Selector selector = Selector.open();
+
+ ServerSocketChannel ssChannel = ServerSocketChannel.open();
+ ssChannel.configureBlocking(false);
+ ssChannel.register(selector, SelectionKey.OP_ACCEPT);
+
+ ServerSocket serverSocket = ssChannel.socket();
+ InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8888);
+ serverSocket.bind(address);
+
+ while (true) {
+
+ selector.select();
+ Set keys = selector.selectedKeys();
+ Iterator keyIterator = keys.iterator();
+
+ while (keyIterator.hasNext()) {
+
+ SelectionKey key = keyIterator.next();
+
+ if (key.isAcceptable()) {
+
+ ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
+
+ // 服务器会为每个新连接创建一个 SocketChannel
+ SocketChannel sChannel = ssChannel1.accept();
+ sChannel.configureBlocking(false);
+
+ // 这个新连接主要用于从客户端读取数据
+ sChannel.register(selector, SelectionKey.OP_READ);
+
+ } else if (key.isReadable()) {
+
+ SocketChannel sChannel = (SocketChannel) key.channel();
+ System.out.println(readDataFromSocketChannel(sChannel));
+ sChannel.close();
+ }
+
+ keyIterator.remove();
+ }
+ }
+ }
+
+ private static String readDataFromSocketChannel(SocketChannel sChannel) throws IOException {
+
+ ByteBuffer buffer = ByteBuffer.allocate(1024);
+ StringBuilder data = new StringBuilder();
+
+ while (true) {
+
+ buffer.clear();
+ int n = sChannel.read(buffer);
+ if (n == -1) {
+ break;
+ }
+ buffer.flip();
+ int limit = buffer.limit();
+ char[] dst = new char[limit];
+ for (int i = 0; i < limit; i++) {
+ dst[i] = (char) buffer.get(i);
+ }
+ data.append(dst);
+ buffer.clear();
+ }
+ return data.toString();
+ }
+}
+```
+
+```java
+public class NIOClient {
+
+ public static void main(String[] args) throws IOException {
+ Socket socket = new Socket("127.0.0.1", 8888);
+ OutputStream out = socket.getOutputStream();
+ String s = "hello world";
+ out.write(s.getBytes());
+ out.close();
+ }
+}
+```
+
+## 内存映射文件
+
+内存映射文件 I/O 是一种读和写文件数据的方法,它可以比常规的基于流或者基于通道的 I/O 快得多。
+
+向内存映射文件写入可能是危险的,只是改变数组的单个元素这样的简单操作,就可能会直接修改磁盘上的文件。修改数据与将数据保存到磁盘是没有分开的。
+
+下面代码行将文件的前 1024 个字节映射到内存中,map() 方法返回一个 MappedByteBuffer,它是 ByteBuffer 的子类。因此,可以像使用其他任何 ByteBuffer 一样使用新映射的缓冲区,操作系统会在需要时负责执行映射。
+
+```java
+MappedByteBuffer mbb = fc.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
+```
+
+## 对比
+
+NIO 与普通 I/O 的区别主要有以下两点:
+
+- NIO 是非阻塞的
+- NIO 面向块,I/O 面向流
+
+# 八、参考资料
+
+- Eckel B, 埃克尔, 昊鹏, 等. Java 编程思想 [M]. 机械工业出版社, 2002.
+- [IBM: NIO 入门](https://www.ibm.com/developerworks/cn/education/java/j-nio/j-nio.html)
+- [IBM: 深入分析 Java I/O 的工作机制](https://www.ibm.com/developerworks/cn/java/j-lo-javaio/index.html)
+- [IBM: 深入分析 Java 中的中文编码问题](https://www.ibm.com/developerworks/cn/java/j-lo-chinesecoding/index.htm)
+- [IBM: Java 序列化的高级认识](https://www.ibm.com/developerworks/cn/java/j-lo-serial/index.html)
+- [NIO 与传统 IO 的区别](http://blog.csdn.net/shimiso/article/details/24990499)
+- [Decorator Design Pattern](http://stg-tud.github.io/sedc/Lecture/ws13-14/5.3-Decorator.html#mode=document)
+- [Socket Multicast](http://labojava.blogspot.com/2012/12/socket-multicast.html)
+>>>>>>> 8c67483fe9ac599aa6f6358fb32a541d7e279666
diff --git a/notes/Java 容器.md b/notes/Java 容器.md
index 649f563a..b5fbefc6 100644
--- a/notes/Java 容器.md
+++ b/notes/Java 容器.md
@@ -1,4 +1,1155 @@
+<<<<<<< HEAD
+=======
+* [一、概览](#一概览)
+ * [Collection](#collection)
+ * [Map](#map)
+* [二、容器中的设计模式](#二容器中的设计模式)
+ * [迭代器模式](#迭代器模式)
+ * [适配器模式](#适配器模式)
+* [三、源码分析](#三源码分析)
+ * [ArrayList](#arraylist)
+ * [Vector](#vector)
+ * [CopyOnWriteArrayList](#copyonwritearraylist)
+ * [LinkedList](#linkedlist)
+ * [HashMap](#hashmap)
+ * [ConcurrentHashMap](#concurrenthashmap)
+ * [LinkedHashMap](#linkedhashmap)
+ * [WeekHashMap](#weekhashmap)
+* [附录](#附录)
+* [参考资料](#参考资料)
+
+
+
+# 一、概览
+
+容器主要包括 Collection 和 Map 两种,Collection 又包含了 List、Set 以及 Queue。
+
+## Collection
+
+
+
+### 1. Set
+
+- HashSet:基于哈希表实现,支持快速查找。但不支持有序性操作,例如根据一个范围查找元素的操作。并且失去了元素的插入顺序信息,也就是说使用 Iterator 遍历 HashSet 得到的结果是不确定的。
+
+- TreeSet:基于红黑树实现,支持有序性操作,但是查找效率不如 HashSet,HashSet 查找时间复杂度为 O(1),TreeSet 则为 O(logN)。
+
+- LinkedHashSet:具有 HashSet 的查找效率,且内部使用双向链表维护元素的插入顺序。
+
+### 2. List
+
+- ArrayList:基于动态数组实现,支持随机访问。
+
+- Vector:和 ArrayList 类似,但它是线程安全的。
+
+- LinkedList:基于双向链表实现,只能顺序访问,但是可以快速地在链表中间插入和删除元素。不仅如此,LinkedList 还可以用作栈、队列和双向队列。
+
+### 3. Queue
+
+- LinkedList:可以用它来实现双向队列。
+
+- PriorityQueue:基于堆结构实现,可以用它来实现优先队列。
+
+## Map
+
+
+
+- HashMap:基于哈希表实现;
+
+- HashTable:和 HashMap 类似,但它是线程安全的,这意味着同一时刻多个线程可以同时写入 HashTable 并且不会导致数据不一致。它是遗留类,不应该去使用它。现在可以使用 ConcurrentHashMap 来支持线程安全,并且 ConcurrentHashMap 的效率会更高,因为 ConcurrentHashMap 引入了分段锁。
+
+- LinkedHashMap:使用双向链表来维护元素的顺序,顺序为插入顺序或者最近最少使用(LRU)顺序。
+
+- TreeMap:基于红黑树实现。
+
+# 二、容器中的设计模式
+
+## 迭代器模式
+
+
+
+Collection 实现了 Iterable 接口,其中的 iterator() 方法能够产生一个 Iterator 对象,通过这个对象就可以迭代遍历 Collection 中的元素。
+
+从 JDK 1.5 之后可以使用 foreach 方法来遍历实现了 Iterable 接口的聚合对象。
+
+```java
+List list = new ArrayList<>();
+list.add("a");
+list.add("b");
+for (String item : list) {
+ System.out.println(item);
+}
+```
+
+## 适配器模式
+
+java.util.Arrays#asList() 可以把数组类型转换为 List 类型。
+
+```java
+@SafeVarargs
+public static List asList(T... a)
+```
+
+应该注意的是 asList() 的参数为泛型的变长参数,不能使用基本类型数组作为参数,只能使用相应的包装类型数组。
+
+```java
+Integer[] arr = {1, 2, 3};
+List list = Arrays.asList(arr);
+```
+
+也可以使用以下方式调用 asList():
+
+```java
+List list = Arrays.asList(1,2,3);
+```
+
+# 三、源码分析
+
+如果没有特别说明,以下源码分析基于 JDK 1.8。
+
+在 IDEA 中 double shift 调出 Search EveryWhere,查找源码文件,找到之后就可以阅读源码。
+
+## ArrayList
+
+### 1. 概览
+
+实现了 RandomAccess 接口,因此支持随机访问。这是理所当然的,因为 ArrayList 是基于数组实现的。
+
+```java
+public class ArrayList extends AbstractList
+ implements List, RandomAccess, Cloneable, java.io.Serializable
+```
+
+数组的默认大小为 10。
+
+```java
+private static final int DEFAULT_CAPACITY = 10;
+```
+
+### 2. 序列化
+
+ArrayList 基于数组实现,并且具有动态扩容特性,因此保存元素的数组不一定都会被使用,那么就没必要全部进行序列化。
+
+保存元素的数组 elementData 使用 transient 修饰,该关键字声明数组默认不会被序列化。ArrayList 重写了 writeObject() 和 readObject() 来控制只序列化数组中有元素填充那部分内容。
+
+```java
+transient Object[] elementData; // non-private to simplify nested class access
+```
+
+### 3. 扩容
+
+添加元素时使用 ensureCapacityInternal() 方法来保证容量足够,如果不够时,需要使用 grow() 方法进行扩容,新容量的大小为 `oldCapacity + (oldCapacity >> 1)`,也就是旧容量的 1.5 倍。
+
+扩容操作需要调用 `Arrays.copyOf()` 把原数组整个复制到新数组中,这个操作代价很高,因此最好在创建 ArrayList 对象时就指定大概的容量大小,减少扩容操作的次数。
+
+```java
+public boolean add(E e) {
+ ensureCapacityInternal(size + 1); // Increments modCount!!
+ elementData[size++] = e;
+ return true;
+}
+
+private void ensureCapacityInternal(int minCapacity) {
+ if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
+ minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
+ }
+ ensureExplicitCapacity(minCapacity);
+}
+
+private void ensureExplicitCapacity(int minCapacity) {
+ modCount++;
+ // overflow-conscious code
+ if (minCapacity - elementData.length > 0)
+ grow(minCapacity);
+}
+
+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);
+}
+```
+
+### 4. 删除元素
+
+需要调用 System.arraycopy() 将 index+1 后面的元素都复制到 index 位置上,该操作的时间复杂度为 O(N),可以看出 ArrayList 删除元素的代价是非常高的。
+
+```java
+public E remove(int index) {
+ rangeCheck(index);
+ modCount++;
+ E oldValue = elementData(index);
+ int numMoved = size - index - 1;
+ if (numMoved > 0)
+ System.arraycopy(elementData, index+1, elementData, index, numMoved);
+ elementData[--size] = null; // clear to let GC do its work
+ return oldValue;
+}
+```
+
+### 5. Fail-Fast
+
+modCount 用来记录 ArrayList 结构发生变化的次数。结构发生变化是指添加或者删除至少一个元素的所有操作,或者是调整内部数组的大小,仅仅只是设置元素的值不算结构发生变化。
+
+在进行序列化或者迭代等操作时,需要比较操作前后 modCount 是否改变,如果改变了需要抛出 ConcurrentModificationException。
+
+```java
+private void writeObject(java.io.ObjectOutputStream s)
+ throws java.io.IOException{
+ // Write out element count, and any hidden stuff
+ int expectedModCount = modCount;
+ s.defaultWriteObject();
+
+ // Write out size as capacity for behavioural compatibility with clone()
+ s.writeInt(size);
+
+ // Write out all elements in the proper order.
+ for (int i=0; i= elementCount)
+ throw new ArrayIndexOutOfBoundsException(index);
+
+ return elementData(index);
+}
+```
+
+### 2. 与 ArrayList 的区别
+
+- Vector 是同步的,因此开销就比 ArrayList 要大,访问速度更慢。最好使用 ArrayList 而不是 Vector,因为同步操作完全可以由程序员自己来控制;
+- Vector 每次扩容请求其大小的 2 倍空间,而 ArrayList 是 1.5 倍。
+
+### 3. 替代方案
+
+为了获得线程安全的 ArrayList,可以使用 `Collections.synchronizedList();` 得到一个线程安全的 ArrayList。
+
+```java
+List list = new ArrayList<>();
+List synList = Collections.synchronizedList(list);
+```
+
+也可以使用 concurrent 并发包下的 CopyOnWriteArrayList 类。
+
+```java
+List list = new CopyOnWriteArrayList<>();
+```
+
+## CopyOnWriteArrayList
+
+### 读写分离
+
+写操作在一个复制的数组上进行,读操作还是在原始数组中进行,读写分离,互不影响。
+
+写操作需要加锁,防止同时并发写入时导致的写入数据丢失。
+
+写操作结束之后需要把原始数组指向新的复制数组。
+
+```java
+public boolean add(E e) {
+ final ReentrantLock lock = this.lock;
+ lock.lock();
+ try {
+ Object[] elements = getArray();
+ int len = elements.length;
+ Object[] newElements = Arrays.copyOf(elements, len + 1);
+ newElements[len] = e;
+ setArray(newElements);
+ return true;
+ } finally {
+ lock.unlock();
+ }
+}
+
+final void setArray(Object[] a) {
+ array = a;
+}
+```
+
+```java
+@SuppressWarnings("unchecked")
+private E get(Object[] a, int index) {
+ return (E) a[index];
+}
+```
+
+### 适用场景
+
+CopyOnWriteArrayList 在写操作的同时允许读操作,大大提高了读操作的性能,因此很适合读多写少的应用场景。
+
+但是 CopyOnWriteArrayList 有其缺陷:
+
+- 内存占用:在写操作时需要复制一个新的数组,使得内存占用为原来的两倍左右;
+- 数据不一致:读操作不能读取实时性的数据,因为部分写操作的数据还未同步到读数组中。
+
+所以 CopyOnWriteArrayList 不适合内存敏感以及对实时性要求很高的场景。
+
+## LinkedList
+
+### 1. 概览
+
+基于双向链表实现,使用 Node 存储链表节点信息。
+
+```java
+private static class Node {
+ E item;
+ Node next;
+ Node prev;
+}
+```
+
+每个链表存储了 first 和 last 指针:
+
+```java
+transient Node first;
+transient Node last;
+```
+
+
+
+### 2. ArrayList 与 LinkedList
+
+- ArrayList 基于动态数组实现,LinkedList 基于双向链表实现;
+- ArrayList 支持随机访问,LinkedList 不支持;
+- LinkedList 在任意位置添加删除元素更快。
+
+## HashMap
+
+为了便于理解,以下源码分析以 JDK 1.7 为主。
+
+### 1. 存储结构
+
+内部包含了一个 Entry 类型的数组 table。
+
+```java
+transient Entry[] table;
+```
+
+其中,Entry 就是存储数据的键值对,它包含了四个字段。从 next 字段我们可以看出 Entry 是一个链表,即数组中的每个位置被当成一个桶,一个桶存放一个链表,链表中存放哈希值相同的 Entry。也就是说,HashMap 使用拉链法来解决冲突。
+
+
+
+```java
+static class Entry implements Map.Entry {
+ final K key;
+ V value;
+ Entry next;
+ int hash;
+
+ Entry(int h, K k, V v, Entry n) {
+ value = v;
+ next = n;
+ key = k;
+ hash = h;
+ }
+
+ public final K getKey() {
+ return key;
+ }
+
+ public final V getValue() {
+ return value;
+ }
+
+ public final V setValue(V newValue) {
+ V oldValue = value;
+ value = newValue;
+ return oldValue;
+ }
+
+ public final boolean equals(Object o) {
+ if (!(o instanceof Map.Entry))
+ return false;
+ Map.Entry e = (Map.Entry)o;
+ Object k1 = getKey();
+ Object k2 = e.getKey();
+ if (k1 == k2 || (k1 != null && k1.equals(k2))) {
+ Object v1 = getValue();
+ Object v2 = e.getValue();
+ if (v1 == v2 || (v1 != null && v1.equals(v2)))
+ return true;
+ }
+ return false;
+ }
+
+ public final int hashCode() {
+ return Objects.hashCode(getKey()) ^ Objects.hashCode(getValue());
+ }
+
+ public final String toString() {
+ return getKey() + "=" + getValue();
+ }
+
+ /**
+ * This method is invoked whenever the value in an entry is
+ * overwritten by an invocation of put(k,v) for a key k that's already
+ * in the HashMap.
+ */
+ void recordAccess(HashMap m) {
+ }
+
+ /**
+ * This method is invoked whenever the entry is
+ * removed from the table.
+ */
+ void recordRemoval(HashMap m) {
+ }
+}
+```
+
+### 2. 拉链法的工作原理
+
+```java
+HashMap map = new HashMap<>();
+map.put("K1", "V1");
+map.put("K2", "V2");
+map.put("K3", "V3");
+```
+
+- 新建一个 HashMap,默认大小为 16;
+- 插入 <K1,V1> 键值对,先计算 K1 的 hashCode 为 115,使用除留余数法得到所在的桶下标 115%16=3。
+- 插入 <K2,V2> 键值对,先计算 K2 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6。
+- 插入 <K3,V3> 键值对,先计算 K3 的 hashCode 为 118,使用除留余数法得到所在的桶下标 118%16=6,插在 <K2,V2> 前面。
+
+应该注意到链表的插入是以头插法方式进行的,例如上面的 <K3,V3> 不是插在 <K2,V2> 后面,而是插入在链表头部。
+
+查找需要分成两步进行:
+
+- 计算键值对所在的桶;
+- 在链表上顺序查找,时间复杂度显然和链表的长度成正比。
+
+
+
+### 3. put 操作
+
+```java
+public V put(K key, V value) {
+ if (table == EMPTY_TABLE) {
+ inflateTable(threshold);
+ }
+ // 键为 null 单独处理
+ if (key == null)
+ return putForNullKey(value);
+ int hash = hash(key);
+ // 确定桶下标
+ int i = indexFor(hash, table.length);
+ // 先找出是否已经存在键为 key 的键值对,如果存在的话就更新这个键值对的值为 value
+ for (Entry e = table[i]; e != null; e = e.next) {
+ Object k;
+ if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
+ V oldValue = e.value;
+ e.value = value;
+ e.recordAccess(this);
+ return oldValue;
+ }
+ }
+
+ modCount++;
+ // 插入新键值对
+ addEntry(hash, key, value, i);
+ return null;
+}
+```
+
+HashMap 允许插入键为 null 的键值对。但是因为无法调用 null 的 hashCode() 方法,也就无法确定该键值对的桶下标,只能通过强制指定一个桶下标来存放。HashMap 使用第 0 个桶存放键为 null 的键值对。
+
+```java
+private V putForNullKey(V value) {
+ for (Entry e = table[0]; e != null; e = e.next) {
+ if (e.key == null) {
+ V oldValue = e.value;
+ e.value = value;
+ e.recordAccess(this);
+ return oldValue;
+ }
+ }
+ modCount++;
+ addEntry(0, null, value, 0);
+ return null;
+}
+```
+
+使用链表的头插法,也就是新的键值对插在链表的头部,而不是链表的尾部。
+
+```java
+void addEntry(int hash, K key, V value, int bucketIndex) {
+ if ((size >= threshold) && (null != table[bucketIndex])) {
+ resize(2 * table.length);
+ hash = (null != key) ? hash(key) : 0;
+ bucketIndex = indexFor(hash, table.length);
+ }
+
+ createEntry(hash, key, value, bucketIndex);
+}
+
+void createEntry(int hash, K key, V value, int bucketIndex) {
+ Entry e = table[bucketIndex];
+ // 头插法,链表头部指向新的键值对
+ table[bucketIndex] = new Entry<>(hash, key, value, e);
+ size++;
+}
+```
+
+```java
+Entry(int h, K k, V v, Entry n) {
+ value = v;
+ next = n;
+ key = k;
+ hash = h;
+}
+```
+
+### 4. 确定桶下标
+
+很多操作都需要先确定一个键值对所在的桶下标。
+
+```java
+int hash = hash(key);
+int i = indexFor(hash, table.length);
+```
+
+(一)计算 hash 值
+
+```java
+final int hash(Object k) {
+ int h = hashSeed;
+ if (0 != h && k instanceof String) {
+ return sun.misc.Hashing.stringHash32((String) k);
+ }
+
+ h ^= k.hashCode();
+
+ // This function ensures that hashCodes that differ only by
+ // constant multiples at each bit position have a bounded
+ // number of collisions (approximately 8 at default load factor).
+ h ^= (h >>> 20) ^ (h >>> 12);
+ return h ^ (h >>> 7) ^ (h >>> 4);
+}
+```
+
+```java
+public final int hashCode() {
+ return Objects.hashCode(key) ^ Objects.hashCode(value);
+}
+```
+
+(二)取模
+
+令 x = 1<<4,即 x 为 2 的 4 次方,它具有以下性质:
+
+```
+x : 00010000
+x-1 : 00001111
+```
+
+令一个数 y 与 x-1 做与运算,可以去除 y 位级表示的第 4 位以上数:
+
+```
+y : 10110010
+x-1 : 00001111
+y&(x-1) : 00000010
+```
+
+这个性质和 y 对 x 取模效果是一样的:
+
+```
+x : 00010000
+y : 10110010
+y%x : 00000010
+```
+
+我们知道,位运算的代价比求模运算小的多,因此在进行这种计算时用位运算的话能带来更高的性能。
+
+确定桶下标的最后一步是将 key 的 hash 值对桶个数取模:hash%capacity,如果能保证 capacity 为 2 的 n 次方,那么就可以将这个操作转换为位运算。
+
+```java
+static int indexFor(int h, int length) {
+ return h & (length-1);
+}
+```
+
+### 5. 扩容-基本原理
+
+设 HashMap 的 table 长度为 M,需要存储的键值对数量为 N,如果哈希函数满足均匀性的要求,那么每条链表的长度大约为 N/M,因此平均查找次数的复杂度为 O(N/M)。
+
+为了让查找的成本降低,应该尽可能使得 N/M 尽可能小,因此需要保证 M 尽可能大,也就是说 table 要尽可能大。HashMap 采用动态扩容来根据当前的 N 值来调整 M 值,使得空间效率和时间效率都能得到保证。
+
+和扩容相关的参数主要有:capacity、size、threshold 和 load_factor。
+
+| 参数 | 含义 |
+| :--: | :-- |
+| capacity | table 的容量大小,默认为 16。需要注意的是 capacity 必须保证为 2 的 n 次方。|
+| size | table 的实际使用量。 |
+| threshold | size 的临界值,size 必须小于 threshold,如果大于等于,就必须进行扩容操作。 |
+| loadFactor | 装载因子,table 能够使用的比例,threshold = capacity * loadFactor。|
+
+```java
+static final int DEFAULT_INITIAL_CAPACITY = 16;
+
+static final int MAXIMUM_CAPACITY = 1 << 30;
+
+static final float DEFAULT_LOAD_FACTOR = 0.75f;
+
+transient Entry[] table;
+
+transient int size;
+
+int threshold;
+
+final float loadFactor;
+
+transient int modCount;
+```
+
+从下面的添加元素代码中可以看出,当需要扩容时,令 capacity 为原来的两倍。
+
+```java
+void addEntry(int hash, K key, V value, int bucketIndex) {
+ Entry e = table[bucketIndex];
+ table[bucketIndex] = new Entry<>(hash, key, value, e);
+ if (size++ >= threshold)
+ resize(2 * table.length);
+}
+```
+
+扩容使用 resize() 实现,需要注意的是,扩容操作同样需要把旧 table 的所有键值对重新插入新的 table 中,因此这一步是很费时的。
+
+```java
+void resize(int newCapacity) {
+ Entry[] oldTable = table;
+ int oldCapacity = oldTable.length;
+ if (oldCapacity == MAXIMUM_CAPACITY) {
+ threshold = Integer.MAX_VALUE;
+ return;
+ }
+ Entry[] newTable = new Entry[newCapacity];
+ transfer(newTable);
+ table = newTable;
+ threshold = (int)(newCapacity * loadFactor);
+}
+
+void transfer(Entry[] newTable) {
+ Entry[] src = table;
+ int newCapacity = newTable.length;
+ for (int j = 0; j < src.length; j++) {
+ Entry e = src[j];
+ if (e != null) {
+ src[j] = null;
+ do {
+ Entry next = e.next;
+ int i = indexFor(e.hash, newCapacity);
+ e.next = newTable[i];
+ newTable[i] = e;
+ e = next;
+ } while (e != null);
+ }
+ }
+}
+```
+
+### 6. 扩容-重新计算桶下标
+
+在进行扩容时,需要把键值对重新放到对应的桶上。HashMap 使用了一个特殊的机制,可以降低重新计算桶下标的操作。
+
+假设原数组长度 capacity 为 16,扩容之后 new capacity 为 32:
+
+```html
+capacity : 00010000
+new capacity : 00100000
+```
+
+对于一个 Key,它的哈希值如果在第 6 位上为 0,那么取模得到的结果和之前一样;如果为 1,那么得到的结果为原来的结果 +16。
+
+### 7. 扩容-计算数组容量
+
+HashMap 构造函数允许用户传入的容量不是 2 的 n 次方,因为它可以自动地将传入的容量转换为 2 的 n 次方。
+
+先考虑如何求一个数的掩码,对于 10010000,它的掩码为 11111111,可以使用以下方法得到:
+
+```
+mask |= mask >> 1 11011000
+mask |= mask >> 2 11111100
+mask |= mask >> 4 11111111
+```
+
+mask+1 是大于原始数字的最小的 2 的 n 次方。
+
+```
+num 10010000
+mask+1 100000000
+```
+
+以下是 HashMap 中计算数组容量的代码:
+
+```java
+static final int tableSizeFor(int cap) {
+ int n = cap - 1;
+ n |= n >>> 1;
+ n |= n >>> 2;
+ n |= n >>> 4;
+ n |= n >>> 8;
+ n |= n >>> 16;
+ return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1;
+}
+```
+
+### 8. 链表转红黑树
+
+从 JDK 1.8 开始,一个桶存储的链表长度大于 8 时会将链表转换为红黑树。
+
+### 9. HashMap 与 HashTable
+
+- HashTable 使用 synchronized 来进行同步。
+- HashMap 可以插入键为 null 的 Entry。
+- HashMap 的迭代器是 fail-fast 迭代器。
+- HashMap 不能保证随着时间的推移 Map 中的元素次序是不变的。
+
+## ConcurrentHashMap
+
+### 1. 存储结构
+
+```java
+static final class HashEntry {
+ final int hash;
+ final K key;
+ volatile V value;
+ volatile HashEntry next;
+}
+```
+
+ConcurrentHashMap 和 HashMap 实现上类似,最主要的差别是 ConcurrentHashMap 采用了分段锁(Segment),每个分段锁维护着几个桶(HashEntry),多个线程可以同时访问不同分段锁上的桶,从而使其并发度更高(并发度就是 Segment 的个数)。
+
+Segment 继承自 ReentrantLock。
+
+```java
+static final class Segment extends ReentrantLock implements Serializable {
+
+ private static final long serialVersionUID = 2249069246763182397L;
+
+ static final int MAX_SCAN_RETRIES =
+ Runtime.getRuntime().availableProcessors() > 1 ? 64 : 1;
+
+ transient volatile HashEntry[] table;
+
+ transient int count;
+
+ transient int modCount;
+
+ transient int threshold;
+
+ final float loadFactor;
+}
+```
+
+```java
+final Segment[] segments;
+```
+
+默认的并发级别为 16,也就是说默认创建 16 个 Segment。
+
+```java
+static final int DEFAULT_CONCURRENCY_LEVEL = 16;
+```
+
+
+
+### 2. size 操作
+
+每个 Segment 维护了一个 count 变量来统计该 Segment 中的键值对个数。
+
+```java
+/**
+ * The number of elements. Accessed only either within locks
+ * or among other volatile reads that maintain visibility.
+ */
+transient int count;
+```
+
+在执行 size 操作时,需要遍历所有 Segment 然后把 count 累计起来。
+
+ConcurrentHashMap 在执行 size 操作时先尝试不加锁,如果连续两次不加锁操作得到的结果一致,那么可以认为这个结果是正确的。
+
+尝试次数使用 RETRIES_BEFORE_LOCK 定义,该值为 2,retries 初始值为 -1,因此尝试次数为 3。
+
+如果尝试的次数超过 3 次,就需要对每个 Segment 加锁。
+
+```java
+
+/**
+ * Number of unsynchronized retries in size and containsValue
+ * methods before resorting to locking. This is used to avoid
+ * unbounded retries if tables undergo continuous modification
+ * which would make it impossible to obtain an accurate result.
+ */
+static final int RETRIES_BEFORE_LOCK = 2;
+
+public int size() {
+ // Try a few times to get accurate count. On failure due to
+ // continuous async changes in table, resort to locking.
+ final Segment[] segments = this.segments;
+ int size;
+ boolean overflow; // true if size overflows 32 bits
+ long sum; // sum of modCounts
+ long last = 0L; // previous sum
+ int retries = -1; // first iteration isn't retry
+ try {
+ for (;;) {
+ // 超过尝试次数,则对每个 Segment 加锁
+ if (retries++ == RETRIES_BEFORE_LOCK) {
+ for (int j = 0; j < segments.length; ++j)
+ ensureSegment(j).lock(); // force creation
+ }
+ sum = 0L;
+ size = 0;
+ overflow = false;
+ for (int j = 0; j < segments.length; ++j) {
+ Segment seg = segmentAt(segments, j);
+ if (seg != null) {
+ sum += seg.modCount;
+ int c = seg.count;
+ if (c < 0 || (size += c) < 0)
+ overflow = true;
+ }
+ }
+ // 连续两次得到的结果一致,则认为这个结果是正确的
+ if (sum == last)
+ break;
+ last = sum;
+ }
+ } finally {
+ if (retries > RETRIES_BEFORE_LOCK) {
+ for (int j = 0; j < segments.length; ++j)
+ segmentAt(segments, j).unlock();
+ }
+ }
+ return overflow ? Integer.MAX_VALUE : size;
+}
+```
+
+### 3. JDK 1.8 的改动
+
+JDK 1.7 使用分段锁机制来实现并发更新操作,核心类为 Segment,它继承自重入锁 ReentrantLock,并发度与 Segment 数量相等。
+
+JDK 1.8 使用了 CAS 操作来支持更高的并发度,在 CAS 操作失败时使用内置锁 synchronized。
+
+并且 JDK 1.8 的实现也在链表过长时会转换为红黑树。
+
+## LinkedHashMap
+
+### 存储结构
+
+继承自 HashMap,因此具有和 HashMap 一样的快速查找特性。
+
+```java
+public class LinkedHashMap extends HashMap implements Map
+```
+
+内存维护了一个双向链表,用来维护插入顺序或者 LRU 顺序。
+
+```java
+/**
+ * The head (eldest) of the doubly linked list.
+ */
+transient LinkedHashMap.Entry head;
+
+/**
+ * The tail (youngest) of the doubly linked list.
+ */
+transient LinkedHashMap.Entry tail;
+```
+
+accessOrder 决定了顺序,默认为 false,此时使用的是插入顺序。
+
+```java
+final boolean accessOrder;
+```
+
+LinkedHashMap 最重要的是以下用于维护顺序的函数,它们会在 put、get 等方法中调用。
+
+```java
+void afterNodeAccess(Node p) { }
+void afterNodeInsertion(boolean evict) { }
+```
+
+### afterNodeAccess()
+
+当一个节点被访问时,如果 accessOrder 为 true,则会将 该节点移到链表尾部。也就是说指定为 LRU 顺序之后,在每次访问一个节点时,会将这个节点移到链表尾部,保证链表尾部是最近访问的节点,那么链表首部就是最近最久未使用的节点。
+
+```java
+void afterNodeAccess(Node e) { // move node to last
+ LinkedHashMap.Entry last;
+ if (accessOrder && (last = tail) != e) {
+ LinkedHashMap.Entry p =
+ (LinkedHashMap.Entry)e, b = p.before, a = p.after;
+ p.after = null;
+ if (b == null)
+ head = a;
+ else
+ b.after = a;
+ if (a != null)
+ a.before = b;
+ else
+ last = b;
+ if (last == null)
+ head = p;
+ else {
+ p.before = last;
+ last.after = p;
+ }
+ tail = p;
+ ++modCount;
+ }
+}
+```
+
+### afterNodeInsertion()
+
+在 put 等操作之后执行,当 removeEldestEntry() 方法返回 ture 时会移除最晚的节点,也就是链表首部节点 first。
+
+evict 只有在构建 Map 的时候才为 false,在这里为 true。
+
+```java
+void afterNodeInsertion(boolean evict) { // possibly remove eldest
+ LinkedHashMap.Entry first;
+ if (evict && (first = head) != null && removeEldestEntry(first)) {
+ K key = first.key;
+ removeNode(hash(key), key, null, false, true);
+ }
+}
+```
+
+removeEldestEntry() 默认为 false,如果需要让它为 true,需要继承 LinkedHashMap 并且覆盖这个方法的实现,这在实现 LRU 的缓存中特别有用,通过移除最近最久未使用的节点,从而保证缓存空间足够,并且缓存的数据都是热点数据。
+
+```java
+protected boolean removeEldestEntry(Map.Entry eldest) {
+ return false;
+ }
+```
+
+### LRU 缓存
+
+以下是使用 LinkedHashMap 实现的一个 LRU 缓存:
+
+- 设定最大缓存空间 MAX_ENTRIES 为 3;
+- 使用 LinkedHashMap 的构造函数将 accessOrder 设置为 true,开启 LUR 顺序;
+- 覆盖 removeEldestEntry() 方法实现,在节点多于 MAX_ENTRIES 就会将最近最久未使用的数据移除。
+
+```java
+class LRUCache extends LinkedHashMap {
+ private static final int MAX_ENTRIES = 3;
+
+ protected boolean removeEldestEntry(Map.Entry eldest) {
+ return size() > MAX_ENTRIES;
+ }
+
+ LRUCache() {
+ super(MAX_ENTRIES, 0.75f, true);
+ }
+}
+```
+
+```java
+public static void main(String[] args) {
+ LRUCache cache = new LRUCache<>();
+ cache.put(1, "a");
+ cache.put(2, "b");
+ cache.put(3, "c");
+ cache.get(1);
+ cache.put(4, "d");
+ System.out.println(cache.keySet());
+}
+```
+
+```html
+[3, 1, 4]
+```
+
+## WeekHashMap
+
+### 存储结构
+
+WeakHashMap 的 Entry 继承自 WeakReference,被 WeakReference 关联的对象在下一次垃圾回收时会被回收。
+
+WeakHashMap 主要用来实现缓存,通过使用 WeakHashMap 来引用缓存对象,由 JVM 对这部分缓存进行回收。
+
+```java
+private static class Entry extends WeakReference