主要基于jdk8, 可能会有些特性与jdk7之前不相同, 例如LinkedList LinkedHashMap中的双向列表不再是回环的. HashMap中的单链表是尾插, 而不是头插入等等, 后文不再赘叙这些差异, 本文目录结构如下: LinkedList 经典的双链表结构, 适用于乱序插入, 删除. 指定序列操作则性能不如ArrayList, 这也是其数据结构决定的. add(E) / addLast(E) add(index, E) 这边有个小的优化, 他会先判断index是靠近队头还是队尾, 来确定从哪个方向遍历链入. 1 if (index < (size="">> 1)) { 2 Node 3 for (int i = 0; i < index;=""> 4 x = x.next; 5 return x; 6 } else { 7 Node 8 for (int i = size - 1; i > index; i--) 9 x = x.prev; 10 return x; 11 } 靠队尾 get(index) 也是会先判断index, 不过性能依然不好, 这也是为什么不推荐用for(int i = 0; i < lengh;="" i++)的方式遍历linkedlist,=""> remove(E) ArrayList 底层就是一个数组, 因此按序查找快, 乱序插入, 删除因为涉及到后面元素移位所以性能慢. add(index, E) 扩容 一般默认容量是10, 扩容后, 会length*1.5. remove(E) 循环遍历数组, 判断E是否equals当前元素, 删除性能不如LinkedList. Stack 经典的数据结构, 底层也是数组, 继承自Vector, 先进后出FILO, 默认new Stack()容量为10, 超出自动扩容. push(E) pop() 后缀表达式 Stack的一个典型应用就是计算表达式如 9 + (3 - 1) * 3 + 10 / 2, 计算机将中缀表达式转为后缀表达式, 再对后缀表达式进行计算. 中缀转后缀 计算后缀表达 队列 与Stack的区别在于, Stack的删除与添加都在队尾进行, 而Queue删除在队头, 添加在队尾. ArrayBlockingQueue 生产消费者中常用的阻塞有界队列, FIFO. put(E) put(E) 队列满了 1 final ReentrantLock lock = this.lock; 2 lock.lockInterruptibly(); 3 try { 4 while (count == items.length) 5 notFull.await(); 6 enqueue(e); 7 } finally { 8 lock.unlock(); 9 } take() 当元素被取出后, 并没有对数组后面的元素位移, 而是更新takeIndex来指向下一个元素. takeIndex是一个环形的增长, 当移动到队列尾部时, 会指向0, 再次循环. 1 private E dequeue() { 2 // assert lock.getHoldCount() == 1; 3 // assert items[takeIndex] != null; 4 final Object[] items = this.items; 5 @SuppressWarnings('unchecked') 6 E x = (E) items[takeIndex]; 7 items[takeIndex] = null; 8 if (++takeIndex == items.length) 9 takeIndex = 0; 10 count--; 11 if (itrs != null) 12 itrs.elementDequeued(); 13 notFull.signal(); 14 return x; 15 } HashMap 最常用的哈希表, 面试的童鞋必备知识了, 内部通过数组 + 单链表的方式实现. jdk8中引入了红黑树对长度 > 8的链表进行优化, 我们另外篇幅再讲. put(K, V) put(K, V) 相同hash值 resize 动态扩容 当map中元素超出设定的阈值后, 会进行resize (length * 2)操作, 扩容过程中对元素一通操作, 并放置到新的位置. 具体操作如下: 1 //定义两条链 2 //原来的hash值新增的bit为0的链,头部和尾部 3 Node 4 //原来的hash值新增的bit为1的链,头部和尾部 5 Node 6 Node 7 //循环遍历出链条链 8 do { 9 next = e.next; 10 if ((e.hash & oldCap) == 0) { 11 if (loTail == null) 12 loHead = e; 13 else 14 loTail.next = e; 15 loTail = e; 16 } 17 else { 18 if (hiTail == null) 19 hiHead = e; 20 else 21 hiTail.next = e; 22 hiTail = e; 23 } 24 } while ((e = next) != null); 25 //扩容前后位置不变的链 26 if (loTail != null) { 27 loTail.next = null; 28 newTab[j] = loHead; 29 } 30 //扩容后位置加上原数组长度的链 31 if (hiTail != null) { 32 hiTail.next = null; 33 newTab[j + oldCap] = hiHead; 34 } LinkedHashMap 继承自HashMap, 底层额外维护了一个双向链表来维持数据有序. 可以通过设置accessOrder来实现FIFO(插入有序)或者LRU(访问有序)缓存. put(K, V) get(K) accessOrder为false的时候, 直接返回元素就行了, 不需要调整位置. accessOrder为true的时候, 需要将最近访问的元素, 放置到队尾. removeEldestEntry 删除最老的元素 |
|
来自: 昵称25832105 > 《信息》