增加HaspMap和LinkedList相关内容
This commit is contained in:
parent
ad9b991fc4
commit
896c62d3e7
|
@ -0,0 +1,457 @@
|
|||
### <font face="楷体"> **目录:**</font>
|
||||
<a href="#1" target="_self">0-1. 简介</a>
|
||||
|
||||
<a href="#2" target="_self">0-2. 内部结构分析</a>
|
||||
|
||||
<a href="#2.1" target="_self">0-2-1. JDK18之前</a>
|
||||
|
||||
<a href="#2.2" target="_self">0-2-2. JDK18之后</a>
|
||||
|
||||
<a href="#3" target="_self">0-3. LinkedList源码分析</a>
|
||||
|
||||
<a href="#3.1" target="_self">0-3-1. 构造方法</a>
|
||||
|
||||
<a href="#3.2" target="_self">0-3-2. put方法</a>
|
||||
|
||||
<a href="#3.3" target="_self">0-3-3. get方法</a>
|
||||
|
||||
<a href="#3.4" target="_self">0-3-4. resize方法</a>
|
||||
|
||||
<a href="#4" target="_self">0-4. HashMap常用方法测试</a>
|
||||
## <font face="楷体" id="1">简介</font>
|
||||
<font color="red">HashMap</font>主要用来存放<font color="red">键值对</font>,它<font color="red">基于哈希表的Map接口实现</font>,是常用的Java集合之一。与HashTable主要区别为<font color="red">不支持同步和允许null作为key和value</font>,所以如果你想要保证线程安全,可以使用<font color="red">ConcurrentHashMap</font>代替而不是线程安全的HashTable,因为HashTable基本已经被淘汰。
|
||||
## <font face="楷体" id="2">内部结构分析
|
||||
### <font face="楷体" id="2.1">JDK1.8之前:</font>
|
||||
JDK1.8之前HashMap底层是<font color="red">数组和链表</font>结合在一起使用也就是<font color="red">链表散列</font>。HashMap通过key的hashCode来计算hash值,当hashCode相同时,通过<font color="red">“拉链法”</font>解决冲突。
|
||||
|
||||
所谓<font color="red">“拉链法”</font>就是:将链表和数组相结合。也就是说创建一个链表数组,数组中每一格就是一个链表。若遇到哈希冲突,则将冲突的值加到链表中即可。
|
||||
![jdk1.8之前的内部结构](https://user-gold-cdn.xitu.io/2018/3/20/16240dbcc303d872?w=348&h=427&f=png&s=10991)
|
||||
简单来说,JDK1.8之前HashMap由<font color="red">数组+链表组成的,数组是HashMap的主体,链表则是主要为了解决哈希冲突而存在的,如果定位到的数组位置不含链表(当前entry的next指向null),那么对于查找,添加等操作很快,仅需一次寻址即可;如果定位到的数组包含链表,对于添加操作,其时间复杂度依然为O(1),因为最新的Entry会插入链表头部,急需要简单改变引用链即可,而对于查找操作来讲,此时就需要遍历链表,然后通过key对象的equals方法逐一比对查找.</font>
|
||||
### <font face="楷体" id="2.2">JDK1.8之后:</font>
|
||||
相比于之前的版本,jdk1.8在解决哈希冲突时有了较大的变化,当链表长度大于阈值(默认为8)时,将链表转化为红黑树,以减少搜索时间。
|
||||
![JDK1.8之后的内部结构](https://user-gold-cdn.xitu.io/2018/3/20/16240e0e30123cfc?w=552&h=519&f=png&s=15827)
|
||||
**类的属性:**
|
||||
```java
|
||||
public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneable, Serializable {
|
||||
// 序列号
|
||||
private static final long serialVersionUID = 362498820763181265L;
|
||||
// 默认的初始容量是16
|
||||
static final int DEFAULT_INITIAL_CAPACITY = 1 << 4;
|
||||
// 最大容量
|
||||
static final int MAXIMUM_CAPACITY = 1 << 30;
|
||||
// 默认的填充因子
|
||||
static final float DEFAULT_LOAD_FACTOR = 0.75f;
|
||||
// 当桶(bucket)上的结点数大于这个值时会转成红黑树
|
||||
static final int TREEIFY_THRESHOLD = 8;
|
||||
// 当桶(bucket)上的结点数小于这个值时树转链表
|
||||
static final int UNTREEIFY_THRESHOLD = 6;
|
||||
// 桶中结构转化为红黑树对应的table的最小大小
|
||||
static final int MIN_TREEIFY_CAPACITY = 64;
|
||||
// 存储元素的数组,总是2的幂次倍
|
||||
transient Node<k,v>[] table;
|
||||
// 存放具体元素的集
|
||||
transient Set<map.entry<k,v>> entrySet;
|
||||
// 存放元素的个数,注意这个不等于数组的长度。
|
||||
transient int size;
|
||||
// 每次扩容和更改map结构的计数器
|
||||
transient int modCount;
|
||||
// 临界值 当实际大小(容量*填充因子)超过临界值时,会进行扩容
|
||||
int threshold;
|
||||
// 填充因子
|
||||
final float loadFactor;
|
||||
}
|
||||
```
|
||||
<font color="red">(1)loadFactor加载因子</font>
|
||||
|
||||
loadFactor加载因子是控制数组存放数据的疏密程度,loadFactor越趋近于1,那么 数组中存放的数据(entry)也就越多,也就越密,也就是会让链表的长度增加,load Factor越小,也就是趋近于0,
|
||||
|
||||
**loadFactor太大导致查找元素效率低,太小导致数组的利用率低,存放的数据会很分散。loadFactor的默认值为0.75f是官方给出的一个比较好的临界值**。
|
||||
|
||||
<font color="red">(2)threshold</font>
|
||||
|
||||
**threshold = capacity * loadFactor**,**当Size>=threshold**的时候,那么就要考虑对数组的扩增了,也就是说,这个的意思就是 **衡量数组是否需要扩增的一个标准**。
|
||||
|
||||
**Node节点类源码:**
|
||||
```java
|
||||
// 继承自 Map.Entry<K,V>
|
||||
static class Node<K,V> implements Map.Entry<K,V> {
|
||||
final int hash;// 哈希值,存放元素到hashmap中时用来与其他元素hash值比较
|
||||
final K key;//键
|
||||
V value;//值
|
||||
// 指向下一个节点
|
||||
Node<K,V> next;
|
||||
Node(int hash, K key, V value, Node<K,V> next) {
|
||||
this.hash = hash;
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.next = next;
|
||||
}
|
||||
public final K getKey() { return key; }
|
||||
public final V getValue() { return value; }
|
||||
public final String toString() { return key + "=" + value; }
|
||||
// 重写hashCode()方法
|
||||
public final int hashCode() {
|
||||
return Objects.hashCode(key) ^ Objects.hashCode(value);
|
||||
}
|
||||
|
||||
public final V setValue(V newValue) {
|
||||
V oldValue = value;
|
||||
value = newValue;
|
||||
return oldValue;
|
||||
}
|
||||
// 重写 equals() 方法
|
||||
public final boolean equals(Object o) {
|
||||
if (o == this)
|
||||
return true;
|
||||
if (o instanceof Map.Entry) {
|
||||
Map.Entry<?,?> e = (Map.Entry<?,?>)o;
|
||||
if (Objects.equals(key, e.getKey()) &&
|
||||
Objects.equals(value, e.getValue()))
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
```
|
||||
**树节点类源码:**
|
||||
```java
|
||||
static final class TreeNode<K,V> extends LinkedHashMap.Entry<K,V> {
|
||||
TreeNode<K,V> parent; // 父
|
||||
TreeNode<K,V> left; // 左
|
||||
TreeNode<K,V> right; // 右
|
||||
TreeNode<K,V> prev; // needed to unlink next upon deletion
|
||||
boolean red; // 判断颜色
|
||||
TreeNode(int hash, K key, V val, Node<K,V> next) {
|
||||
super(hash, key, val, next);
|
||||
}
|
||||
// 返回根节点
|
||||
final TreeNode<K,V> root() {
|
||||
for (TreeNode<K,V> r = this, p;;) {
|
||||
if ((p = r.parent) == null)
|
||||
return r;
|
||||
r = p;
|
||||
}
|
||||
```
|
||||
## <font face="楷体" id="3">HashMap源码分析</font>
|
||||
### <font face="楷体" id="3.1">构造方法</font>
|
||||
![四个构造方法](https://user-gold-cdn.xitu.io/2018/3/20/162410d912a2e0e1?w=336&h=90&f=jpeg&s=26744)
|
||||
```java
|
||||
// 默认构造函数。
|
||||
public More ...HashMap() {
|
||||
this.loadFactor = DEFAULT_LOAD_FACTOR; // all other fields defaulted
|
||||
}
|
||||
|
||||
// 包含另一个“Map”的构造函数
|
||||
public More ...HashMap(Map<? extends K, ? extends V> m) {
|
||||
this.loadFactor = DEFAULT_LOAD_FACTOR;
|
||||
putMapEntries(m, false);//下面会分析到这个方法
|
||||
}
|
||||
|
||||
// 指定“容量大小”的构造函数
|
||||
public More ...HashMap(int initialCapacity) {
|
||||
this(initialCapacity, DEFAULT_LOAD_FACTOR);
|
||||
}
|
||||
|
||||
// 指定“容量大小”和“加载因子”的构造函数
|
||||
public More ...HashMap(int initialCapacity, float loadFactor) {
|
||||
if (initialCapacity < 0)
|
||||
throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity);
|
||||
if (initialCapacity > MAXIMUM_CAPACITY)
|
||||
initialCapacity = MAXIMUM_CAPACITY;
|
||||
if (loadFactor <= 0 || Float.isNaN(loadFactor))
|
||||
throw new IllegalArgumentException("Illegal load factor: " + loadFactor);
|
||||
this.loadFactor = loadFactor;
|
||||
this.threshold = tableSizeFor(initialCapacity);
|
||||
}
|
||||
```
|
||||
putMapEntries方法:
|
||||
```java
|
||||
final void putMapEntries(Map<? extends K, ? extends V> m, boolean evict) {
|
||||
int s = m.size();
|
||||
if (s > 0) {
|
||||
// 判断table是否已经初始化
|
||||
if (table == null) { // pre-size
|
||||
// 未初始化,s为m的实际元素个数
|
||||
float ft = ((float)s / loadFactor) + 1.0F;
|
||||
int t = ((ft < (float)MAXIMUM_CAPACITY) ?
|
||||
(int)ft : MAXIMUM_CAPACITY);
|
||||
// 计算得到的t大于阈值,则初始化阈值
|
||||
if (t > threshold)
|
||||
threshold = tableSizeFor(t);
|
||||
}
|
||||
// 已初始化,并且m元素个数大于阈值,进行扩容处理
|
||||
else if (s > threshold)
|
||||
resize();
|
||||
// 将m中的所有元素添加至HashMap中
|
||||
for (Map.Entry<? extends K, ? extends V> e : m.entrySet()) {
|
||||
K key = e.getKey();
|
||||
V value = e.getValue();
|
||||
putVal(hash(key), key, value, false, evict);
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.2">put方法</font>
|
||||
HashMap只提供了put用于添加元素,putVal方法只是给put方法调用的一个方法,并没有提供给用户使用。
|
||||
```java
|
||||
public V put(K key, V value) {
|
||||
return putVal(hash(key), key, value, false, true);
|
||||
}
|
||||
|
||||
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
|
||||
boolean evict) {
|
||||
Node<K,V>[] tab; Node<K,V> p; int n, i;
|
||||
// table未初始化或者长度为0,进行扩容
|
||||
if ((tab = table) == null || (n = tab.length) == 0)
|
||||
n = (tab = resize()).length;
|
||||
// (n - 1) & hash 确定元素存放在哪个桶中,桶为空,新生成结点放入桶中(此时,这个结点是放在数组中)
|
||||
if ((p = tab[i = (n - 1) & hash]) == null)
|
||||
tab[i] = newNode(hash, key, value, null);
|
||||
// 桶中已经存在元素
|
||||
else {
|
||||
Node<K,V> e; K k;
|
||||
// 比较桶中第一个元素(数组中的结点)的hash值相等,key相等
|
||||
if (p.hash == hash &&
|
||||
((k = p.key) == key || (key != null && key.equals(k))))
|
||||
// 将第一个元素赋值给e,用e来记录
|
||||
e = p;
|
||||
// hash值不相等,即key不相等;为红黑树结点
|
||||
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;
|
||||
}
|
||||
// 判断链表中结点的key值与插入的元素的key值是否相等
|
||||
if (e.hash == hash &&
|
||||
((k = e.key) == key || (key != null && key.equals(k))))
|
||||
// 相等,跳出循环
|
||||
break;
|
||||
// 用于遍历桶中的链表,与前面的e = p.next组合,可以遍历链表
|
||||
p = e;
|
||||
}
|
||||
}
|
||||
// 表示在桶中找到key值、hash值与插入元素相等的结点
|
||||
if (e != null) {
|
||||
// 记录e的value
|
||||
V oldValue = e.value;
|
||||
// onlyIfAbsent为false或者旧值为null
|
||||
if (!onlyIfAbsent || oldValue == null)
|
||||
//用新值替换旧值
|
||||
e.value = value;
|
||||
// 访问后回调
|
||||
afterNodeAccess(e);
|
||||
// 返回旧值
|
||||
return oldValue;
|
||||
}
|
||||
}
|
||||
// 结构性修改
|
||||
++modCount;
|
||||
// 实际大小大于阈值则扩容
|
||||
if (++size > threshold)
|
||||
resize();
|
||||
// 插入后回调
|
||||
afterNodeInsertion(evict);
|
||||
return null;
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.3">get方法</font>
|
||||
```java
|
||||
public V get(Object key) {
|
||||
Node<K,V> e;
|
||||
return (e = getNode(hash(key), key)) == null ? null : e.value;
|
||||
}
|
||||
|
||||
final Node<K,V> getNode(int hash, Object key) {
|
||||
Node<K,V>[] tab; Node<K,V> first, e; int n; K k;
|
||||
if ((tab = table) != null && (n = tab.length) > 0 &&
|
||||
(first = tab[(n - 1) & hash]) != null) {
|
||||
// 数组元素相等
|
||||
if (first.hash == hash && // always check first node
|
||||
((k = first.key) == key || (key != null && key.equals(k))))
|
||||
return first;
|
||||
// 桶中不止一个节点
|
||||
if ((e = first.next) != null) {
|
||||
// 在树中get
|
||||
if (first instanceof TreeNode)
|
||||
return ((TreeNode<K,V>)first).getTreeNode(hash, key);
|
||||
// 在链表中get
|
||||
do {
|
||||
if (e.hash == hash &&
|
||||
((k = e.key) == key || (key != null && key.equals(k))))
|
||||
return e;
|
||||
} while ((e = e.next) != null);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.4">resize方法</font>
|
||||
进行扩容,会伴随着一次重新hash分配,并且会遍历hash表中所有的元素,是非常耗时的。在编写程序中,要尽量避免resize。
|
||||
```java
|
||||
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;
|
||||
}
|
||||
// 没超过最大值,就扩充为原来的2倍
|
||||
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 {
|
||||
signifies using defaults
|
||||
newCap = DEFAULT_INITIAL_CAPACITY;
|
||||
newThr = (int)(DEFAULT_LOAD_FACTOR * DEFAULT_INITIAL_CAPACITY);
|
||||
}
|
||||
// 计算新的resize上限
|
||||
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) {
|
||||
// 把每个bucket都移动到新的buckets中
|
||||
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 {
|
||||
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;
|
||||
}
|
||||
// 原索引+oldCap
|
||||
else {
|
||||
if (hiTail == null)
|
||||
hiHead = e;
|
||||
else
|
||||
hiTail.next = e;
|
||||
hiTail = e;
|
||||
}
|
||||
} while ((e = next) != null);
|
||||
// 原索引放到bucket里
|
||||
if (loTail != null) {
|
||||
loTail.next = null;
|
||||
newTab[j] = loHead;
|
||||
}
|
||||
// 原索引+oldCap放到bucket里
|
||||
if (hiTail != null) {
|
||||
hiTail.next = null;
|
||||
newTab[j + oldCap] = hiHead;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return newTab;
|
||||
}
|
||||
```
|
||||
## <font face="楷体" id="4">HashMap常用方法测试</font>
|
||||
```java
|
||||
package map;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
public class HashMapDemo {
|
||||
|
||||
public static void main(String[] args) {
|
||||
HashMap<String, String> map = new HashMap<String, String>();
|
||||
// 键不能重复,值可以重复
|
||||
map.put("san", "张三");
|
||||
map.put("si", "李四");
|
||||
map.put("wu", "王五");
|
||||
map.put("wang", "老王");
|
||||
map.put("wang", "老王2");// 老王被覆盖
|
||||
map.put("lao", "老王");
|
||||
System.out.println("-------直接输出hashmap:-------");
|
||||
System.out.println(map);
|
||||
/**
|
||||
* 遍历HashMap
|
||||
*/
|
||||
// 1.获取Map中的所有键
|
||||
System.out.println("-------foreach获取Map中所有的键:------");
|
||||
Set<String> keys = map.keySet();
|
||||
for (String key : keys) {
|
||||
System.out.print(key+" ");
|
||||
}
|
||||
System.out.println();//换行
|
||||
// 2.获取Map中所有值
|
||||
System.out.println("-------foreach获取Map中所有的值:------");
|
||||
Collection<String> values = map.values();
|
||||
for (String value : values) {
|
||||
System.out.print(value+" ");
|
||||
}
|
||||
System.out.println();//换行
|
||||
// 3.得到key的值的同时得到key所对应的值
|
||||
System.out.println("-------得到key的值的同时得到key所对应的值:-------");
|
||||
Set<String> keys2 = map.keySet();
|
||||
for (String key : keys2) {
|
||||
System.out.print(key + ":" + map.get(key)+" ");
|
||||
|
||||
}
|
||||
/**
|
||||
* 另外一种不常用的遍历方式
|
||||
*/
|
||||
// 当我调用put(key,value)方法的时候,首先会把key和value封装到
|
||||
// Entry这个静态内部类对象中,把Entry对象再添加到数组中,所以我们想获取
|
||||
// map中的所有键值对,我们只要获取数组中的所有Entry对象,接下来
|
||||
// 调用Entry对象中的getKey()和getValue()方法就能获取键值对了
|
||||
Set<java.util.Map.Entry<String, String>> entrys = map.entrySet();
|
||||
for (java.util.Map.Entry<String, String> entry : entrys) {
|
||||
System.out.println(entry.getKey() + "--" + entry.getValue());
|
||||
}
|
||||
|
||||
/**
|
||||
* HashMap其他常用方法
|
||||
*/
|
||||
System.out.println("after map.size():"+map.size());
|
||||
System.out.println("after map.isEmpty():"+map.isEmpty());
|
||||
System.out.println(map.remove("san"));
|
||||
System.out.println("after map.remove():"+map);
|
||||
System.out.println("after map.get(si):"+map.get("si"));
|
||||
System.out.println("after map.containsKey(si):"+map.containsKey("si"));
|
||||
System.out.println("after containsValue(李四):"+map.containsValue("李四"));
|
||||
System.out.println(map.replace("si", "李四2"));
|
||||
System.out.println("after map.replace(si, 李四2):"+map);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
```
|
|
@ -0,0 +1,518 @@
|
|||
<a href="#1" target="_self">0-1. 简介</a>
|
||||
|
||||
<a href="#2" target="_self">0-2. 内部结构分析</a>
|
||||
|
||||
<a href="#3" target="_self">0-3. LinkedList源码分析</a>
|
||||
|
||||
<a href="#3.1" target="_self">0-3-1. 构造方法</a>
|
||||
|
||||
<a href="#3.2" target="_self">0-3-2. 添加add方法</a>
|
||||
|
||||
<a href="#3.3" target="_self">0-3-3. 根据位置取数据的方法</a>
|
||||
|
||||
<a href="#3.4" target="_self">0-3-4. 根据对象得到索引的方法</a>
|
||||
|
||||
<a href="#3.5" target="_self">0-3-5. 检查链表是否包含某对象的方法</a>
|
||||
|
||||
<a href="#3.6" target="_self">0-3-6. 删除removepop方法</a>
|
||||
|
||||
<a href="#4" target="_self">0-4. LinkedList类常用方法</a>
|
||||
## <font face="楷体" id="1"> 简介</font>
|
||||
<font color="red">LinkedList</font>是一个实现了<font color="red">List接口</font>和<font color="red">Deque接口</font>的<font color="red">双端链表</font>。
|
||||
LinkedList底层的链表结构使它<font color="red">支持高效的插入和删除操作</font>,另外它实现了Deque接口,使得LinkedList类也具有队列的特性;
|
||||
LinkedList<font color="red">不是线程安全的</font>,如果想使LinkedList变成线程安全的,可以调用静态类<font color="red">Collections类</font>中的<font color="red">synchronizedList</font>方法:
|
||||
```java
|
||||
List list=Collections.synchronizedList(new LinkedList(...));
|
||||
```
|
||||
## <font face="楷体" id="2">内部结构分析</font>
|
||||
**如下图所示:**
|
||||
![LinkedList内部结构](https://user-gold-cdn.xitu.io/2018/3/19/1623e363fe0450b0?w=600&h=481&f=jpeg&s=18502)
|
||||
看完了图之后,我们再看LinkedList类中的一个<font color="red">**内部私有类Node**</font>就很好理解了:
|
||||
```java
|
||||
private static class Node<E> {
|
||||
E item;//节点值
|
||||
Node<E> next;//前驱节点
|
||||
Node<E> prev;//后继节点
|
||||
|
||||
Node(Node<E> prev, E element, Node<E> next) {
|
||||
this.item = element;
|
||||
this.next = next;
|
||||
this.prev = prev;
|
||||
}
|
||||
}
|
||||
```
|
||||
这个类就代表双端链表的节点Node。这个类有三个属性,分别是前驱节点,本节点的值,后继结点。
|
||||
|
||||
## <font face="楷体" id="3"> LinkedList源码分析</font>
|
||||
### <font face="楷体" id="3.1">构造方法</font>
|
||||
**空构造方法:**
|
||||
```java
|
||||
public LinkedList() {
|
||||
}
|
||||
```
|
||||
**用已有的集合创建链表的构造方法:**
|
||||
```java
|
||||
public LinkedList(Collection<? extends E> c) {
|
||||
this();
|
||||
addAll(c);
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.2">添加(add)方法</font>
|
||||
**add(E e)** 方法:将元素添加到链表尾部
|
||||
```java
|
||||
public boolean add(E e) {
|
||||
linkLast(e);//这里就只调用了这一个方法
|
||||
return true;
|
||||
}
|
||||
```
|
||||
|
||||
```java
|
||||
/**
|
||||
* 链接使e作为最后一个元素。
|
||||
*/
|
||||
void linkLast(E e) {
|
||||
final Node<E> l = last;
|
||||
final Node<E> newNode = new Node<>(l, e, null);
|
||||
last = newNode;//新建节点
|
||||
if (l == null)
|
||||
first = newNode;
|
||||
else
|
||||
l.next = newNode;//指向后继元素也就是指向下一个元素
|
||||
size++;
|
||||
modCount++;
|
||||
}
|
||||
```
|
||||
**add(int index,E e)**:在指定位置添加元素
|
||||
```java
|
||||
public void add(int index, E element) {
|
||||
checkPositionIndex(index); //检查索引是否处于[0-size]之间
|
||||
|
||||
if (index == size)//添加在链表尾部
|
||||
linkLast(element);
|
||||
else//添加在链表中间
|
||||
linkBefore(element, node(index));
|
||||
}
|
||||
```
|
||||
<font color="red">linkBefore方法</font>需要给定两个参数,一个<font color="red">插入节点的值</font>,一个<font color="red">指定的node</font>,所以我们又调用了<font color="red">Node(index)去找到index对应的node</font>
|
||||
|
||||
**addAll(Collection c ):将集合插入到链表尾部**
|
||||
|
||||
```java
|
||||
public boolean addAll(Collection<? extends E> c) {
|
||||
return addAll(size, c);
|
||||
}
|
||||
```
|
||||
**addAll(int index, Collection c):** 将集合从指定位置开始插入
|
||||
```java
|
||||
public boolean addAll(int index, Collection<? extends E> c) {
|
||||
//1:检查index范围是否在size之内
|
||||
checkPositionIndex(index);
|
||||
|
||||
//2:toArray()方法把集合的数据存到对象数组中
|
||||
Object[] a = c.toArray();
|
||||
int numNew = a.length;
|
||||
if (numNew == 0)
|
||||
return false;
|
||||
|
||||
//3:得到插入位置的前驱节点和后继节点
|
||||
Node<E> pred, succ;
|
||||
//如果插入位置为尾部,前驱节点为last,后继节点为null
|
||||
if (index == size) {
|
||||
succ = null;
|
||||
pred = last;
|
||||
}
|
||||
//否则,调用node()方法得到后继节点,再得到前驱节点
|
||||
else {
|
||||
succ = node(index);
|
||||
pred = succ.prev;
|
||||
}
|
||||
|
||||
// 4:遍历数据将数据插入
|
||||
for (Object o : a) {
|
||||
@SuppressWarnings("unchecked") E e = (E) o;
|
||||
//创建新节点
|
||||
Node<E> newNode = new Node<>(pred, e, null);
|
||||
//如果插入位置在链表头部
|
||||
if (pred == null)
|
||||
first = newNode;
|
||||
else
|
||||
pred.next = newNode;
|
||||
pred = newNode;
|
||||
}
|
||||
|
||||
//如果插入位置在尾部,重置last节点
|
||||
if (succ == null) {
|
||||
last = pred;
|
||||
}
|
||||
//否则,将插入的链表与先前链表连接起来
|
||||
else {
|
||||
pred.next = succ;
|
||||
succ.prev = pred;
|
||||
}
|
||||
|
||||
size += numNew;
|
||||
modCount++;
|
||||
return true;
|
||||
}
|
||||
```
|
||||
上面可以看出addAll方法通常包括下面四个步骤:
|
||||
1. 检查index范围是否在size之内
|
||||
2. toArray()方法把集合的数据存到对象数组中
|
||||
3. 得到插入位置的前驱和后继节点
|
||||
4. 遍历数据,将数据插入到指定位置
|
||||
|
||||
**addFirst(E e):** 将元素添加到链表头部
|
||||
```java
|
||||
public void addFirst(E e) {
|
||||
linkFirst(e);
|
||||
}
|
||||
```
|
||||
```java
|
||||
private void linkFirst(E e) {
|
||||
final Node<E> f = first;
|
||||
final Node<E> newNode = new Node<>(null, e, f);//新建节点,以头节点为后继节点
|
||||
first = newNode;
|
||||
//如果链表为空,last节点也指向该节点
|
||||
if (f == null)
|
||||
last = newNode;
|
||||
//否则,将头节点的前驱指针指向新节点,也就是指向前一个元素
|
||||
else
|
||||
f.prev = newNode;
|
||||
size++;
|
||||
modCount++;
|
||||
}
|
||||
```
|
||||
**addLast(E e):** 将元素添加到链表尾部,与 **add(E e)** 方法一样
|
||||
```java
|
||||
public void addLast(E e) {
|
||||
linkLast(e);
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.3">根据位置取数据的方法</font>
|
||||
**get(int index):**:根据指定索引返回数据
|
||||
```java
|
||||
public E get(int index) {
|
||||
//检查index范围是否在size之内
|
||||
checkElementIndex(index);
|
||||
//调用Node(index)去找到index对应的node然后返回它的值
|
||||
return node(index).item;
|
||||
}
|
||||
```
|
||||
**获取头节点(index=0)数据方法:**
|
||||
```java
|
||||
public E getFirst() {
|
||||
final Node<E> f = first;
|
||||
if (f == null)
|
||||
throw new NoSuchElementException();
|
||||
return f.item;
|
||||
}
|
||||
public E element() {
|
||||
return getFirst();
|
||||
}
|
||||
public E peek() {
|
||||
final Node<E> f = first;
|
||||
return (f == null) ? null : f.item;
|
||||
}
|
||||
|
||||
public E peekFirst() {
|
||||
final Node<E> f = first;
|
||||
return (f == null) ? null : f.item;
|
||||
}
|
||||
```
|
||||
**区别:**
|
||||
getFirst(),element(),peek(),peekFirst()
|
||||
这四个获取头结点方法的区别在于对链表为空时的处理,是抛出异常还是返回null,其中**getFirst()** 和**element()** 方法将会在链表为空时,抛出异常
|
||||
|
||||
element()方法的内部就是使用getFirst()实现的。它们会在链表为空时,抛出NoSuchElementException
|
||||
**获取尾节点(index=-1)数据方法:**
|
||||
```java
|
||||
public E getLast() {
|
||||
final Node<E> l = last;
|
||||
if (l == null)
|
||||
throw new NoSuchElementException();
|
||||
return l.item;
|
||||
}
|
||||
public E peekLast() {
|
||||
final Node<E> l = last;
|
||||
return (l == null) ? null : l.item;
|
||||
}
|
||||
```
|
||||
**两者区别:**
|
||||
**getLast()** 方法在链表为空时,会抛出**NoSuchElementException**,而**peekLast()** 则不会,只是会返回 **null**。
|
||||
### <font face="楷体" id="3.4">根据对象得到索引的方法</font>
|
||||
**int indexOf(Object o):** 从头遍历找
|
||||
```java
|
||||
public int indexOf(Object o) {
|
||||
int index = 0;
|
||||
if (o == null) {
|
||||
//从头遍历
|
||||
for (Node<E> x = first; x != null; x = x.next) {
|
||||
if (x.item == null)
|
||||
return index;
|
||||
index++;
|
||||
}
|
||||
} else {
|
||||
//从头遍历
|
||||
for (Node<E> x = first; x != null; x = x.next) {
|
||||
if (o.equals(x.item))
|
||||
return index;
|
||||
index++;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
**int lastIndexOf(Object o):** 从尾遍历找
|
||||
```java
|
||||
public int lastIndexOf(Object o) {
|
||||
int index = size;
|
||||
if (o == null) {
|
||||
//从尾遍历
|
||||
for (Node<E> x = last; x != null; x = x.prev) {
|
||||
index--;
|
||||
if (x.item == null)
|
||||
return index;
|
||||
}
|
||||
} else {
|
||||
//从尾遍历
|
||||
for (Node<E> x = last; x != null; x = x.prev) {
|
||||
index--;
|
||||
if (o.equals(x.item))
|
||||
return index;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
```
|
||||
### <font face="楷体" id="3.5">检查链表是否包含某对象的方法:</font>
|
||||
**contains(Object o):** 检查对象o是否存在于链表中
|
||||
```java
|
||||
public boolean contains(Object o) {
|
||||
return indexOf(o) != -1;
|
||||
}
|
||||
```
|
||||
###<font face="楷体" id="3.6"> 删除(remove/pop)方法</font>
|
||||
**remove()** ,**removeFirst(),pop():** 删除头节点
|
||||
```
|
||||
public E pop() {
|
||||
return removeFirst();
|
||||
}
|
||||
public E remove() {
|
||||
return removeFirst();
|
||||
}
|
||||
public E removeFirst() {
|
||||
final Node<E> f = first;
|
||||
if (f == null)
|
||||
throw new NoSuchElementException();
|
||||
return unlinkFirst(f);
|
||||
}
|
||||
```
|
||||
**removeLast(),pollLast():** 删除尾节点
|
||||
```java
|
||||
public E removeLast() {
|
||||
final Node<E> l = last;
|
||||
if (l == null)
|
||||
throw new NoSuchElementException();
|
||||
return unlinkLast(l);
|
||||
}
|
||||
public E pollLast() {
|
||||
final Node<E> l = last;
|
||||
return (l == null) ? null : unlinkLast(l);
|
||||
}
|
||||
```
|
||||
**区别:** removeLast()在链表为空时将抛出NoSuchElementException,而pollLast()方法返回null。
|
||||
|
||||
**remove(Object o):** 删除指定元素
|
||||
```java
|
||||
public boolean remove(Object o) {
|
||||
//如果删除对象为null
|
||||
if (o == null) {
|
||||
//从头开始遍历
|
||||
for (Node<E> x = first; x != null; x = x.next) {
|
||||
//找到元素
|
||||
if (x.item == null) {
|
||||
//从链表中移除找到的元素
|
||||
unlink(x);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
//从头开始遍历
|
||||
for (Node<E> x = first; x != null; x = x.next) {
|
||||
//找到元素
|
||||
if (o.equals(x.item)) {
|
||||
//从链表中移除找到的元素
|
||||
unlink(x);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
```
|
||||
当删除指定对象时,只需调用remove(Object o)即可,不过该方法一次只会删除一个匹配的对象,如果删除了匹配对象,返回true,否则false。
|
||||
|
||||
unlink(Node<E> x) 方法:
|
||||
```java
|
||||
E unlink(Node<E> x) {
|
||||
// assert x != null;
|
||||
final E element = x.item;
|
||||
final Node<E> next = x.next;//得到后继节点
|
||||
final Node<E> prev = x.prev;//得到前驱节点
|
||||
|
||||
//删除前驱指针
|
||||
if (prev == null) {
|
||||
first = next;如果删除的节点是头节点,令头节点指向该节点的后继节点
|
||||
} else {
|
||||
prev.next = next;//将前驱节点的后继节点指向后继节点
|
||||
x.prev = null;
|
||||
}
|
||||
|
||||
//删除后继指针
|
||||
if (next == null) {
|
||||
last = prev;//如果删除的节点是尾节点,令尾节点指向该节点的前驱节点
|
||||
} else {
|
||||
next.prev = prev;
|
||||
x.next = null;
|
||||
}
|
||||
|
||||
x.item = null;
|
||||
size--;
|
||||
modCount++;
|
||||
return element;
|
||||
}
|
||||
```
|
||||
**remove(int index)**:删除指定位置的元素
|
||||
```java
|
||||
public E remove(int index) {
|
||||
//检查index范围
|
||||
checkElementIndex(index);
|
||||
//将节点删除
|
||||
return unlink(node(index));
|
||||
}
|
||||
```
|
||||
## <font face="楷体" id="4">LinkedList类常用方法测试</font>:
|
||||
|
||||
```java
|
||||
package list;
|
||||
|
||||
import java.util.Iterator;
|
||||
import java.util.LinkedList;
|
||||
|
||||
public class LinkedListDemo {
|
||||
public static void main(String[] srgs) {
|
||||
//创建存放int类型的linkedList
|
||||
LinkedList<Integer> linkedList = new LinkedList<>();
|
||||
/************************** linkedList的基本操作 ************************/
|
||||
linkedList.addFirst(0); // 添加元素到列表开头
|
||||
linkedList.add(1); // 在列表结尾添加元素
|
||||
linkedList.add(2, 2); // 在指定位置添加元素
|
||||
linkedList.addLast(3); // 添加元素到列表结尾
|
||||
|
||||
System.out.println("LinkedList(直接输出的): " + linkedList);
|
||||
|
||||
System.out.println("getFirst()获得第一个元素: " + linkedList.getFirst()); // 返回此列表的第一个元素
|
||||
System.out.println("getLast()获得第最后一个元素: " + linkedList.getLast()); // 返回此列表的最后一个元素
|
||||
System.out.println("removeFirst()删除第一个元素并返回: " + linkedList.removeFirst()); // 移除并返回此列表的第一个元素
|
||||
System.out.println("removeLast()删除最后一个元素并返回: " + linkedList.removeLast()); // 移除并返回此列表的最后一个元素
|
||||
System.out.println("After remove:" + linkedList);
|
||||
System.out.println("contains()方法判断列表是否包含1这个元素:" + linkedList.contains(1)); // 判断此列表包含指定元素,如果是,则返回true
|
||||
System.out.println("该linkedList的大小 : " + linkedList.size()); // 返回此列表的元素个数
|
||||
|
||||
/************************** 位置访问操作 ************************/
|
||||
System.out.println("-----------------------------------------");
|
||||
linkedList.set(1, 3); // 将此列表中指定位置的元素替换为指定的元素
|
||||
System.out.println("After set(1, 3):" + linkedList);
|
||||
System.out.println("get(1)获得指定位置(这里为1)的元素: " + linkedList.get(1)); // 返回此列表中指定位置处的元素
|
||||
|
||||
/************************** Search操作 ************************/
|
||||
System.out.println("-----------------------------------------");
|
||||
linkedList.add(3);
|
||||
System.out.println("indexOf(3): " + linkedList.indexOf(3)); // 返回此列表中首次出现的指定元素的索引
|
||||
System.out.println("lastIndexOf(3): " + linkedList.lastIndexOf(3));// 返回此列表中最后出现的指定元素的索引
|
||||
|
||||
/************************** Queue操作 ************************/
|
||||
System.out.println("-----------------------------------------");
|
||||
System.out.println("peek(): " + linkedList.peek()); // 获取但不移除此列表的头
|
||||
System.out.println("element(): " + linkedList.element()); // 获取但不移除此列表的头
|
||||
linkedList.poll(); // 获取并移除此列表的头
|
||||
System.out.println("After poll():" + linkedList);
|
||||
linkedList.remove();
|
||||
System.out.println("After remove():" + linkedList); // 获取并移除此列表的头
|
||||
linkedList.offer(4);
|
||||
System.out.println("After offer(4):" + linkedList); // 将指定元素添加到此列表的末尾
|
||||
|
||||
/************************** Deque操作 ************************/
|
||||
System.out.println("-----------------------------------------");
|
||||
linkedList.offerFirst(2); // 在此列表的开头插入指定的元素
|
||||
System.out.println("After offerFirst(2):" + linkedList);
|
||||
linkedList.offerLast(5); // 在此列表末尾插入指定的元素
|
||||
System.out.println("After offerLast(5):" + linkedList);
|
||||
System.out.println("peekFirst(): " + linkedList.peekFirst()); // 获取但不移除此列表的第一个元素
|
||||
System.out.println("peekLast(): " + linkedList.peekLast()); // 获取但不移除此列表的第一个元素
|
||||
linkedList.pollFirst(); // 获取并移除此列表的第一个元素
|
||||
System.out.println("After pollFirst():" + linkedList);
|
||||
linkedList.pollLast(); // 获取并移除此列表的最后一个元素
|
||||
System.out.println("After pollLast():" + linkedList);
|
||||
linkedList.push(2); // 将元素推入此列表所表示的堆栈(插入到列表的头)
|
||||
System.out.println("After push(2):" + linkedList);
|
||||
linkedList.pop(); // 从此列表所表示的堆栈处弹出一个元素(获取并移除列表第一个元素)
|
||||
System.out.println("After pop():" + linkedList);
|
||||
linkedList.add(3);
|
||||
linkedList.removeFirstOccurrence(3); // 从此列表中移除第一次出现的指定元素(从头部到尾部遍历列表)
|
||||
System.out.println("After removeFirstOccurrence(3):" + linkedList);
|
||||
linkedList.removeLastOccurrence(3); // 从此列表中移除最后一次出现的指定元素(从头部到尾部遍历列表)
|
||||
System.out.println("After removeFirstOccurrence(3):" + linkedList);
|
||||
|
||||
/************************** 遍历操作 ************************/
|
||||
System.out.println("-----------------------------------------");
|
||||
linkedList.clear();
|
||||
for (int i = 0; i < 100000; i++) {
|
||||
linkedList.add(i);
|
||||
}
|
||||
// 迭代器遍历
|
||||
long start = System.currentTimeMillis();
|
||||
Iterator<Integer> iterator = linkedList.iterator();
|
||||
while (iterator.hasNext()) {
|
||||
iterator.next();
|
||||
}
|
||||
long end = System.currentTimeMillis();
|
||||
System.out.println("Iterator:" + (end - start) + " ms");
|
||||
|
||||
// 顺序遍历(随机遍历)
|
||||
start = System.currentTimeMillis();
|
||||
for (int i = 0; i < linkedList.size(); i++) {
|
||||
linkedList.get(i);
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("for:" + (end - start) + " ms");
|
||||
|
||||
// 另一种for循环遍历
|
||||
start = System.currentTimeMillis();
|
||||
for (Integer i : linkedList)
|
||||
;
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("for2:" + (end - start) + " ms");
|
||||
|
||||
// 通过pollFirst()或pollLast()来遍历LinkedList
|
||||
LinkedList<Integer> temp1 = new LinkedList<>();
|
||||
temp1.addAll(linkedList);
|
||||
start = System.currentTimeMillis();
|
||||
while (temp1.size() != 0) {
|
||||
temp1.pollFirst();
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("pollFirst()或pollLast():" + (end - start) + " ms");
|
||||
|
||||
// 通过removeFirst()或removeLast()来遍历LinkedList
|
||||
LinkedList<Integer> temp2 = new LinkedList<>();
|
||||
temp2.addAll(linkedList);
|
||||
start = System.currentTimeMillis();
|
||||
while (temp2.size() != 0) {
|
||||
temp2.removeFirst();
|
||||
}
|
||||
end = System.currentTimeMillis();
|
||||
System.out.println("removeFirst()或removeLast():" + (end - start) + " ms");
|
||||
}
|
||||
}
|
||||
```
|
Loading…
Reference in New Issue