Java技术栈.基础篇—详说集合之一

Myth丶恋晨 2022-05-23 03:29 277阅读 0赞

一、集合与数组

数组:(可以存储基本数据类型)是用来存取对象的一种容器,数组的长度固定,不适合在对象数量未知的情况下使用。
集合:(只能存储对象,对象类型可以不一样)集合与数组最大不同:长度可变,可在对象数量未知的情况下使用,使用比较广泛。

集合总览

这里写图片描述

Collection:接口是集合类的根接口,Java中没有提供这个接口的直接实现类。但是却被继承产生了两个接口:Set和List。Set中不能包含重复的元素。List是一个有序的集合,可以包含重复的元素,提供了按索引访问的方式。

Map:是Java.util包中的另一个接口,它和Collection接口没有关系,是相互独立的,但是都属于集合类的一部分。Map包含了key-value对。Map不能包含重复的key,但是可以包含相同的value。

Iterator:所有的集合类,都实现了Iterator接口,这是一个用于遍历集合中元素的接口,主要包含以下三种方法:
1.hasNext()是否还有下一个元素。
2.next()返回下一个元素。
3.remove()删除当前元素。

Collection接口的共性方法:
这里把Collection接口中的共性方法单独拿出来说一下,

  1. //增加 将指定对象存储到容器中 add 方法的参数类型是Object 便于接收任意对象
  2. 1add()
  3. //将指定集合中的元素添加到调用该方法的集合中
  4. 2addAll()
  5. //删除 将指定的对象从集合中删除
  6. 3remove()
  7. //将指定集合中的元素删除
  8. 4removeAll()
  9. //修改 清空集合中的所有元素
  10. 5clear()
  11. / 判断 判断集合是否为空
  12. 6isEmpty()
  13. //判断集合何中是否包含指定对象
  14. 7contains()
  15. //判断集合中是否包含指定集合
  16. 8containsAll()
  17. //判断两个对象是否相等
  18. 9.equals()
  19. //返回集合容器的大小
  20. 10int size()
  21. //集合转换数组
  22. 11 toArray()

List详解

  1. ---|List: 有存储顺序, 可重复
  2. ---|ArrayList: 数组实现, 查找快, 增删慢
  3. 由于是数组实现, 在增和删的时候会牵扯到数组
  4. 增容, 以及拷贝元素. 所以慢。数组是可以直接
  5. 按索引查找, 所以查找时较快
  6. ---|LinkedList: 链表实现, 增删快, 查找慢
  7. 由于链表实现, 增加时只要让前一个元素记住自
  8. 己就可以, 删除时让前一个元素记住后一个元
  9. 素, 后一个元素记住前一个元素. 这样的增删效
  10. 率较高但查询时需要一个一个的遍历, 所以效率
  11. 较低
  12. ---|Vector: ArrayList原理相同, 但线程安全, 效率略低
  13. ArrayList实现方式相同, 但考虑了线程安全问
  14. 题, 所以效率略低

List适合顺序存储,允许重复元素存在,List接口的实现类中常用的是ArrayList和LinkedList,这两个类在使用中是有一定不同的。如果查询较多则使用ArrayList,插入删除变更较多则用LinkedList,而若是对线程安全有要求则使用Vector。

List集合特有方法:

  1. //指定位置添加元素
  2. 1void add(int index, E element)
  3. //指定位置添加集合
  4. 2.boolean addAll(int index, Collection c)
  5. //删除指定位置元素
  6. 3:删除 remove(int index)
  7. //修改集合中的元素 返回的是需要替换的集合中的元素
  8. 4E set(int index, E element)
  9. 5:获取指定索引的元素 注意: IndexOutOfBoundsException
  10. E get(int index)
  11. //获取某个元素的索引 找不到返回-1,有多个时返回第一次出现的位置
  12. 6int indexOf(Object o)
  13. //list允许重复,因此在list中同一个元素可能有多个,此方法返回最后一个
  14. 7lastIndexOf(Object o)
  15. // 求子集合 不包含toIndex
  16. 8 List<E> subList(int fromIndex, int toIndex)

ArrayList

ArrayList就是传说中的动态数组,就是Array的复杂版本,它提供了如下一些好处:
a.动态的增加和减少元素
b.实现了Collection和List接口
c.灵活的设置数组的大小

构造器

ArrayList中有三个构造器:

  1. //默认的构造器,将会以默认(16)的大小来初始化内部的数组
  2. public ArrayList();
  3. //用一个Collection对象来构造,并将该集合的元素添加到ArrayList
  4. public ArrayList(Collection);
  5. //用指定的大小来初始化内部的数组
  6. public ArrayList(int);

ArrayList的同步

IsSynchronized属性和ArrayList.Synchronized方法用于实现ArrayList的同步。
IsSynchronized属性标识当前的ArrayList实例是否支持线程同步,而ArrayList.Synchronized静态方法则会返回一个ArrayList的线程同步的封装。

如果使用非线程同步的实例,那么在多线程访问的时候,需要自己手动调用lock来保持线程同步,例如:

  1. //当ArrayList为非线程包装的时候,SyncRoot属性其实就是它自己,但是为了满
  2. //足Collection的SyncRoot定义,这里还是使用SyncRoot来保持源代码的规范性
  3. ArrayList list = new ArrayList();
  4. lock( list.SyncRoot )
  5. {
  6. list.Add( Add a Item );
  7. }

如果使用ArrayList.Synchronized方法返回的实例,那么就不用考虑线程同步的问题,这个实例本身就是线程安全的,实际上ArrayList内部实现了一个保证线程同步的内部类,ArrayList.Synchronized返回的就是这个类的实例,它里面的每个属性都是用了lock关键字来保证线程同步。

Count属性和Capacity属性

Count属性是目前ArrayList包含的元素的数量,这个属性是只读的。
Capacity属性是目前ArrayList能够包含的最大数量,可以手动的设置这个属性,但是当设置为小于Count值的时候会引发一个异常。

TrimSize方法

这个方法用于将ArrayList固定到实际元素的大小,当动态数组元素确定不在添加的时候,可以调用这个方法来释放空余的内存。

ArrayList与数组转换

例1:

  1. ArrayList List = new ArrayList();
  2. List.Add(1);
  3. List.Add(2);
  4. List.Add(3);
  5. Int32[] values = (Int32[])List.ToArray(typeof(Int32));

例2:

  1. ArrayList List = new ArrayList();
  2. List.Add(1);
  3. List.Add(2);
  4. List.Add(3);
  5. Int32[] values = new Int32[List.Count];
  6. List.CopyTo(values);

上面介绍了两种从ArrayList转换到数组的方法
例3:

  1. ArrayList List = new ArrayList();
  2. List.Add( string );
  3. List.Add( 1 );
  4. //往数组中添加不同类型的元素
  5. object[] values = List.ToArray(typeof(object)); //正确
  6. string[] values = (string[])List.ToArray(typeof(string)); //错误

和数组不一样,因为ArrayList可以转换为Object数组,所以往ArrayList里面添加不同类型的元素是不会出错的,但是当调用ArrayList.ToArray方法的时候,要么传递所有元素都可以正确转型的类型或者Object类型,否则将会抛出无法转型的异常。

ArrayList的使用建议

(1)ArrayList是Array的复杂版本
ArrayList内部封装了一个Object类型的数组,从一般的意义来说,它和数组没有本质的差别,甚至于ArrayList的许多方法,如Index、IndexOf、Contains、Sort等都是在内部数组的基础上直接调用Array的对应方法。
(2)内部的Object类型的影响
对于一般的引用类型来说,这部分的影响不是很大,但是对于值类型来说,往ArrayList里面添加和修改元素,都会引起装箱和拆箱的操作,频繁的操作可能会影响一部分效率。
但是恰恰对于大多数人,多数的应用都是使用值类型的数组。
消除这个影响是没有办法的,除非你不用它,否则就要承担一部分的效率损失,不过这部分的损失不会很大。
(3)数组扩容
这是对ArrayList效率影响比较大的一个因素。
每当执行Add、AddRange、Insert、InsertRange等添加元素的方法,都会检查内部数组的容量是否足够,如果不够,它就会以当前容量的两倍来重新构建一个数组,将旧元素Copy到新数组中,然后丢弃旧数组,在这个临界点的扩容操作,应该来说是比较影响效率的。
例1:比如,一个可能有200个元素的数据动态添加到一个以默认16个元素大小创建的ArrayList中,将会经过:
16*2*2*2*2 = 256
四次的扩容才会满足最终的要求,那么如果一开始就以:

  1. ArrayList List = new ArrayList( 210 );

的方式创建ArrayList,不仅会减少4次数组创建和Copy的操作,还会减少内存使用。

例2:
预计有30个元素而创建了一个ArrayList:

  1. ArrayList List = new ArrayList(30);

在执行过程中,加入了31个元素,那么数组会扩充到60个元素的大小,而这时候不会有新的元素再增加进来,而且有没有调用TrimSize方法,那么就有1次扩容的操作,并且浪费了29个元素大小的空间。如果这时候,用:

  1. ArrayList List = new ArrayList(40);

那么一切都解决了。
所以说,正确的预估可能的元素,并且在适当的时候调用TrimSize方法是提高ArrayList使用效率的重要途径。

效率损失

频繁的调用IndexOf、Contains等方法(Sort、BinarySearch等方法经过优化,不在此列)会引起的效率损失
首先,我们要明确一点,ArrayList是动态数组,它不支持通过Key或者Value快速访问的算法,所以实际上调用IndexOf、Contains等方法是执行的简单的循环来查找元素,所以频繁的调用此类方法并不比你自己写循环并且稍作优化来的快,如果有这方面的要求,建议使用Hashtable或SortedList等键值对的集合。

优缺点

ArrayList类实现了List接口,由ArrayList类实现的List集合采用数组结构保存对象。数组结构的优点是便于对集合进行快速的随机访问,如果经常需要根据索引位置访问集合中的对象,使用由ArrayList类效率较好。
数组结构的缺点是向指定索引位置插入对象和删除指定索引位置对象的速度较慢,如果经常需要向List集合的指定索引位置插入对象,或者是删除List集合的指定索引位置的对象,使用由ArrayList类实现的List集合的效率则较低,并且插入或删除对象的索引位置越小效率越低,原因是当向指定的索引位置插入对象时,会同时将指定索引位置及之后的所有对象相应的向后移动一位。当删除指定索引位置的对象时,会同时将指定索引位置之后的所有对象相应的向前移动一位。如果在指定的索引位置之后有大量的对象,将严重影响对集合的操作效率。
源码解析

  1. <span style="font-family:Microsoft YaHei;">package java.util;
  2. public class ArrayList<E> extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  4. {
  5. // 序列版本号
  6. private static final long serialVersionUID = 8683452581122892189L;
  7. // 保存ArrayList中数据的数组
  8. private transient Object[] elementData;
  9. // ArrayList中实际数据的数量
  10. private int size;
  11. // ArrayList带容量大小的构造函数。
  12. public ArrayList(int initialCapacity) {
  13. super();
  14. if (initialCapacity < 0)
  15. throw new IllegalArgumentException("Illegal Capacity: "+
  16. initialCapacity);
  17. // 新建一个数组
  18. this.elementData = new Object[initialCapacity];
  19. }
  20. // ArrayList构造函数。默认容量是10。
  21. public ArrayList() {
  22. this(10);
  23. }
  24. // 创建一个包含collection的ArrayList
  25. public ArrayList(Collection<? extends E> c) {
  26. elementData = c.toArray();
  27. size = elementData.length;
  28. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  29. if (elementData.getClass() != Object[].class)
  30. elementData = Arrays.copyOf(elementData, size, Object[].class);
  31. }
  32. // 将当前容量值设为 =实际元素个数
  33. public void trimToSize() {
  34. modCount++;
  35. int oldCapacity = elementData.length;
  36. if (size < oldCapacity) {
  37. elementData = Arrays.copyOf(elementData, size);
  38. }
  39. }
  40. // 确定ArrarList的容量。
  41. // 若ArrayList的容量不足以容纳当前的全部元素,设置 新的容量=“(原始容量x3)/2 + 1”
  42. public void ensureCapacity(int minCapacity) {
  43. // 将“修改统计数”+1
  44. modCount++;
  45. int oldCapacity = elementData.length;
  46. // 若当前容量不足以容纳当前的元素个数,设置 新的容量=“(原始容量x3)/2 + 1”
  47. if (minCapacity > oldCapacity) {
  48. Object oldData[] = elementData;
  49. int newCapacity = (oldCapacity * 3)/2 + 1;
  50. if (newCapacity < minCapacity)
  51. newCapacity = minCapacity;
  52. elementData = Arrays.copyOf(elementData, newCapacity);
  53. }
  54. }
  55. // 添加元素e
  56. public boolean add(E e) {
  57. // 确定ArrayList的容量大小
  58. ensureCapacity(size + 1); // Increments modCount!!
  59. // 添加e到ArrayList中
  60. elementData[size++] = e;
  61. return true;
  62. }
  63. // 返回ArrayList的实际大小
  64. public int size() {
  65. return size;
  66. }
  67. // 返回ArrayList是否包含Object(o)
  68. public boolean contains(Object o) {
  69. return indexOf(o) >= 0;
  70. }
  71. // 返回ArrayList是否为空
  72. public boolean isEmpty() {
  73. return size == 0;
  74. }
  75. // 正向查找,返回元素的索引值
  76. public int indexOf(Object o) {
  77. if (o == null) {
  78. for (int i = 0; i < size; i++)
  79. if (elementData[i]==null)
  80. return i;
  81. } else {
  82. for (int i = 0; i < size; i++)
  83. if (o.equals(elementData[i]))
  84. return i;
  85. }
  86. return -1;
  87. }
  88. // 反向查找,返回元素的索引值
  89. public int lastIndexOf(Object o) {
  90. if (o == null) {
  91. for (int i = size-1; i >= 0; i--)
  92. if (elementData[i]==null)
  93. return i;
  94. } else {
  95. for (int i = size-1; i >= 0; i--)
  96. if (o.equals(elementData[i]))
  97. return i;
  98. }
  99. return -1;
  100. }
  101. // 反向查找(从数组末尾向开始查找),返回元素(o)的索引值
  102. public int lastIndexOf(Object o) {
  103. if (o == null) {
  104. for (int i = size-1; i >= 0; i--)
  105. if (elementData[i]==null)
  106. return i;
  107. } else {
  108. for (int i = size-1; i >= 0; i--)
  109. if (o.equals(elementData[i]))
  110. return i;
  111. }
  112. return -1;
  113. }
  114. // 返回ArrayList的Object数组
  115. public Object[] toArray() {
  116. return Arrays.copyOf(elementData, size);
  117. }
  118. // 返回ArrayList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  119. public <T> T[] toArray(T[] a) {
  120. // 若数组a的大小 < ArrayList的元素个数;
  121. // 则新建一个T[]数组,数组大小是“ArrayList的元素个数”,并将“ArrayList”全部拷贝到新数组中
  122. if (a.length < size)
  123. return (T[]) Arrays.copyOf(elementData, size, a.getClass());
  124. // 若数组a的大小 >= ArrayList的元素个数;
  125. // 则将ArrayList的全部元素都拷贝到数组a中。
  126. System.arraycopy(elementData, 0, a, 0, size);
  127. if (a.length > size)
  128. a[size] = null;
  129. return a;
  130. }
  131. // 获取index位置的元素值
  132. public E get(int index) {
  133. RangeCheck(index);
  134. return (E) elementData[index];
  135. }
  136. // 设置index位置的值为element
  137. public E set(int index, E element) {
  138. RangeCheck(index);
  139. E oldValue = (E) elementData[index];
  140. elementData[index] = element;
  141. return oldValue;
  142. }
  143. // 将e添加到ArrayList中
  144. public boolean add(E e) {
  145. ensureCapacity(size + 1); // Increments modCount!!
  146. elementData[size++] = e;
  147. return true;
  148. }
  149. // 将e添加到ArrayList的指定位置
  150. public void add(int index, E element) {
  151. if (index > size || index < 0)
  152. throw new IndexOutOfBoundsException(
  153. "Index: "+index+", Size: "+size);
  154. ensureCapacity(size+1); // Increments modCount!!
  155. System.arraycopy(elementData, index, elementData, index + 1,
  156. size - index);
  157. elementData[index] = element;
  158. size++;
  159. }
  160. // 删除ArrayList指定位置的元素
  161. public E remove(int index) {
  162. RangeCheck(index);
  163. modCount++;
  164. E oldValue = (E) elementData[index];
  165. int numMoved = size - index - 1;
  166. if (numMoved > 0)
  167. System.arraycopy(elementData, index+1, elementData, index,
  168. numMoved);
  169. elementData[--size] = null; // Let gc do its work
  170. return oldValue;
  171. }
  172. // 删除ArrayList的指定元素
  173. public boolean remove(Object o) {
  174. if (o == null) {
  175. for (int index = 0; index < size; index++)
  176. if (elementData[index] == null) {
  177. fastRemove(index);
  178. return true;
  179. }
  180. } else {
  181. for (int index = 0; index < size; index++)
  182. if (o.equals(elementData[index])) {
  183. fastRemove(index);
  184. return true;
  185. }
  186. }
  187. return false;
  188. }
  189. // 快速删除第index个元素
  190. private void fastRemove(int index) {
  191. modCount++;
  192. int numMoved = size - index - 1;
  193. // 从"index+1"开始,用后面的元素替换前面的元素。
  194. if (numMoved > 0)
  195. System.arraycopy(elementData, index+1, elementData, index,
  196. numMoved);
  197. // 将最后一个元素设为null
  198. elementData[--size] = null; // Let gc do its work
  199. }
  200. // 删除元素
  201. public boolean remove(Object o) {
  202. if (o == null) {
  203. for (int index = 0; index < size; index++)
  204. if (elementData[index] == null) {
  205. fastRemove(index);
  206. return true;
  207. }
  208. } else {
  209. // 便利ArrayList,找到“元素o”,则删除,并返回true。
  210. for (int index = 0; index < size; index++)
  211. if (o.equals(elementData[index])) {
  212. fastRemove(index);
  213. return true;
  214. }
  215. }
  216. return false;
  217. }
  218. // 清空ArrayList,将全部的元素设为null
  219. public void clear() {
  220. modCount++;
  221. for (int i = 0; i < size; i++)
  222. elementData[i] = null;
  223. size = 0;
  224. }
  225. // 将集合c追加到ArrayList中
  226. public boolean addAll(Collection<? extends E> c) {
  227. Object[] a = c.toArray();
  228. int numNew = a.length;
  229. ensureCapacity(size + numNew); // Increments modCount
  230. System.arraycopy(a, 0, elementData, size, numNew);
  231. size += numNew;
  232. return numNew != 0;
  233. }
  234. // 从index位置开始,将集合c添加到ArrayList
  235. public boolean addAll(int index, Collection<? extends E> c) {
  236. if (index > size || index < 0)
  237. throw new IndexOutOfBoundsException(
  238. "Index: " + index + ", Size: " + size);
  239. Object[] a = c.toArray();
  240. int numNew = a.length;
  241. ensureCapacity(size + numNew); // Increments modCount
  242. int numMoved = size - index;
  243. if (numMoved > 0)
  244. System.arraycopy(elementData, index, elementData, index + numNew,
  245. numMoved);
  246. System.arraycopy(a, 0, elementData, index, numNew);
  247. size += numNew;
  248. return numNew != 0;
  249. }
  250. // 删除fromIndex到toIndex之间的全部元素。
  251. protected void removeRange(int fromIndex, int toIndex) {
  252. modCount++;
  253. int numMoved = size - toIndex;
  254. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  255. numMoved);
  256. // Let gc do its work
  257. int newSize = size - (toIndex-fromIndex);
  258. while (size != newSize)
  259. elementData[--size] = null;
  260. }
  261. private void RangeCheck(int index) {
  262. if (index >= size)
  263. throw new IndexOutOfBoundsException(
  264. "Index: "+index+", Size: "+size);
  265. }
  266. // 克隆函数
  267. public Object clone() {
  268. try {
  269. ArrayList<E> v = (ArrayList<E>) super.clone();
  270. // 将当前ArrayList的全部元素拷贝到v中
  271. v.elementData = Arrays.copyOf(elementData, size);
  272. v.modCount = 0;
  273. return v;
  274. } catch (CloneNotSupportedException e) {
  275. // this shouldn't happen, since we are Cloneable
  276. throw new InternalError();
  277. }
  278. }
  279. // java.io.Serializable的写入函数
  280. // 将ArrayList的“容量,所有的元素值”都写入到输出流中
  281. private void writeObject(java.io.ObjectOutputStream s)
  282. throws java.io.IOException{
  283. // Write out element count, and any hidden stuff
  284. int expectedModCount = modCount;
  285. s.defaultWriteObject();
  286. // 写入“数组的容量”
  287. s.writeInt(elementData.length);
  288. // 写入“数组的每一个元素”
  289. for (int i=0; i<size; i++)
  290. s.writeObject(elementData[i]);
  291. if (modCount != expectedModCount) {
  292. throw new ConcurrentModificationException();
  293. }
  294. }
  295. // java.io.Serializable的读取函数:根据写入方式读出
  296. // 先将ArrayList的“容量”读出,然后将“所有的元素值”读出
  297. private void readObject(java.io.ObjectInputStream s)
  298. throws java.io.IOException, ClassNotFoundException {
  299. // Read in size, and any hidden stuff
  300. s.defaultReadObject();
  301. // 从输入流中读取ArrayList的“容量”
  302. int arrayLength = s.readInt();
  303. Object[] a = elementData = new Object[arrayLength];
  304. // 从输入流中将“所有的元素值”读出
  305. for (int i=0; i<size; i++)
  306. a[i] = s.readObject();
  307. }
  308. }
  309. </span>

LinkedList

简介

LinkedList 是一个继承于AbstractSequentialList的双向链表。它也可以被当作堆栈、队列或双端队列进行操作。
LinkedList 实现 List 接口,能对它进行队列操作。
LinkedList 实现 Deque 接口,即能将LinkedList当作双端队列使用。
LinkedList 实现了Cloneable接口,即覆盖了函数clone(),能克隆。
LinkedList 实现java.io.Serializable接口,这意味着LinkedList支持序列化,能通过序列化去传输。
LinkedList 是非同步的。

构造函数

  1. // 默认构造函数
  2. LinkedList()
  3. // 创建一个LinkedList,包括Collection中的全部元素。
  4. LinkedList(Collection<? extends E> collection)

LinkedList中的API

  1. LinkedListAPI
  2. boolean add(E object)
  3. void add(int location, E object)
  4. boolean addAll(Collection<? extends E> collection)
  5. boolean addAll(int location, Collection<? extends E> collection)
  6. void addFirst(E object)
  7. void addLast(E object)
  8. void clear()
  9. Object clone()
  10. boolean contains(Object object)
  11. Iterator<E> descendingIterator()
  12. E element()
  13. E get(int location)
  14. E getFirst()
  15. E getLast()
  16. int indexOf(Object object)
  17. int lastIndexOf(Object object)
  18. ListIterator<E> listIterator(int location)
  19. boolean offer(E o)
  20. boolean offerFirst(E e)
  21. boolean offerLast(E e)
  22. E peek()
  23. E peekFirst()
  24. E peekLast()
  25. E poll()
  26. E pollFirst()
  27. E pollLast()
  28. E pop()
  29. void push(E e)
  30. E remove()
  31. E remove(int location)
  32. boolean remove(Object object)
  33. E removeFirst()
  34. boolean removeFirstOccurrence(Object o)
  35. E removeLast()
  36. boolean removeLastOccurrence(Object o)
  37. E set(int location, E object)
  38. int size()
  39. <T> T[] toArray(T[] contents)
  40. Object[] toArray()

AbstractSequentialList简介
LinkedList是AbstractSequentialList的子类。
AbstractSequentialList 实现了get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index)这些方法,这些方法都是支持随机访问List的,LinkedList是双向链表,继承于AbstractSequentialList,也可以通过上述方法随机访问LinkedList的元素。

此外,若需要通过AbstractSequentialList自己实现一个列表,只需要扩展此类,并提供 listIterator() 和 size() 方法的实现即可。若要实现不可修改的列表,则需要实现列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法。

LinkedList数据结构

  1. java.lang.Object
  2. java.util.AbstractCollection<E>
  3. java.util.AbstractList<E>
  4. java.util.AbstractSequentialList<E>
  5. java.util.LinkedList<E>
  6. public class LinkedList<E>
  7. extends AbstractSequentialList<E>
  8. implements List<E>, Deque<E>, Cloneable, java.io.Serializable {
  9. }

这里写图片描述

LinkedList的本质是双向链表。
(1) LinkedList继承于AbstractSequentialList,并且实现了Dequeue接口。
(2) LinkedList包含两个重要的成员:header 和 size。
  header是双向链表的表头,它是双向链表节点所对应的类Entry的实例。Entry中包含成员变量: previous, next, element。其中,previous是该节点的上一个节点,next是该节点的下一个节点,element是该节点所包含的值。 size是双向链表中节点的个数。

源码解析

为了更了解LinkedList的原理,下面对LinkedList源码代码作出分析。
在阅读源码之前,我们先对LinkedList的整体实现进行大致说明:
LinkedList实际上是通过双向链表去实现的。既然是双向链表,那么它的顺序访问会非常高效,而随机访问效率比较低。
LinkedList也实现了List接口,也就是说,它实现了get(int location)、remove(int location)等“根据索引值来获取、删除节点的函数”。LinkedList是如何实现List的这些接口的,如何将“双向链表和索引值联系起来的”?
实际原理非常简单,它就是通过一个计数索引值来实现的。例如,当我们调用get(int location)时,首先会比较“location”和“双向链表长度的1/2”;若后者大,则从链表头开始往后查找,直到location位置;否则,从链表末尾开始先前查找,直到location位置。
这就是“双线链表和索引值联系起来”的方法。

接下来开始阅读源码,只要理解双向链表,那么LinkedList的源码很容易理解的。

  1. package java.util;
  2. public class LinkedList<E>
  3. extends AbstractSequentialList<E>
  4. implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  5. {
  6. // 链表的表头,表头不包含任何数据。Entry是个链表类数据结构。
  7. private transient Entry<E> header = new Entry<E>(null, null, null);
  8. // LinkedList中元素个数
  9. private transient int size = 0;
  10. // 默认构造函数:创建一个空的链表
  11. public LinkedList() {
  12. header.next = header.previous = header;
  13. }
  14. // 包含“集合”的构造函数:创建一个包含“集合”的LinkedList
  15. public LinkedList(Collection<? extends E> c) {
  16. this();
  17. addAll(c);
  18. }
  19. // 获取LinkedList的第一个元素
  20. public E getFirst() {
  21. if (size==0)
  22. throw new NoSuchElementException();
  23. // 链表的表头header中不包含数据。
  24. // 这里返回header所指下一个节点所包含的数据。
  25. return header.next.element;
  26. }
  27. // 获取LinkedList的最后一个元素
  28. public E getLast() {
  29. if (size==0)
  30. throw new NoSuchElementException();
  31. // 由于LinkedList是双向链表;而表头header不包含数据。
  32. // 因而,这里返回表头header的前一个节点所包含的数据。
  33. return header.previous.element;
  34. }
  35. // 删除LinkedList的第一个元素
  36. public E removeFirst() {
  37. return remove(header.next);
  38. }
  39. // 删除LinkedList的最后一个元素
  40. public E removeLast() {
  41. return remove(header.previous);
  42. }
  43. // 将元素添加到LinkedList的起始位置
  44. public void addFirst(E e) {
  45. addBefore(e, header.next);
  46. }
  47. // 将元素添加到LinkedList的结束位置
  48. public void addLast(E e) {
  49. addBefore(e, header);
  50. }
  51. // 判断LinkedList是否包含元素(o)
  52. public boolean contains(Object o) {
  53. return indexOf(o) != -1;
  54. }
  55. // 返回LinkedList的大小
  56. public int size() {
  57. return size;
  58. }
  59. // 将元素(E)添加到LinkedList中
  60. public boolean add(E e) {
  61. // 将节点(节点数据是e)添加到表头(header)之前。
  62. // 即,将节点添加到双向链表的末端。
  63. addBefore(e, header);
  64. return true;
  65. }
  66. // 从LinkedList中删除元素(o)
  67. // 从链表开始查找,如存在元素(o)则删除该元素并返回true;
  68. // 否则,返回false。
  69. public boolean remove(Object o) {
  70. if (o==null) {
  71. // 若o为null的删除情况
  72. for (Entry<E> e = header.next; e != header; e = e.next) {
  73. if (e.element==null) {
  74. remove(e);
  75. return true;
  76. }
  77. }
  78. } else {
  79. // 若o不为null的删除情况
  80. for (Entry<E> e = header.next; e != header; e = e.next) {
  81. if (o.equals(e.element)) {
  82. remove(e);
  83. return true;
  84. }
  85. }
  86. }
  87. return false;
  88. }
  89. // 将“集合(c)”添加到LinkedList中。
  90. // 实际上,是从双向链表的末尾开始,将“集合(c)”添加到双向链表中。
  91. public boolean addAll(Collection<? extends E> c) {
  92. return addAll(size, c);
  93. }
  94. // 从双向链表的index开始,将“集合(c)”添加到双向链表中。
  95. public boolean addAll(int index, Collection<? extends E> c) {
  96. if (index < 0 || index > size)
  97. throw new IndexOutOfBoundsException("Index: "+index+
  98. ", Size: "+size);
  99. Object[] a = c.toArray();
  100. // 获取集合的长度
  101. int numNew = a.length;
  102. if (numNew==0)
  103. return false;
  104. modCount++;
  105. // 设置“当前要插入节点的后一个节点”
  106. Entry<E> successor = (index==size ? header : entry(index));
  107. // 设置“当前要插入节点的前一个节点”
  108. Entry<E> predecessor = successor.previous;
  109. // 将集合(c)全部插入双向链表中
  110. for (int i=0; i<numNew; i++) {
  111. Entry<E> e = new Entry<E>((E)a[i], successor, predecessor);
  112. predecessor.next = e;
  113. predecessor = e;
  114. }
  115. successor.previous = predecessor;
  116. // 调整LinkedList的实际大小
  117. size += numNew;
  118. return true;
  119. }
  120. // 清空双向链表
  121. public void clear() {
  122. Entry<E> e = header.next;
  123. // 从表头开始,逐个向后遍历;对遍历到的节点执行一下操作:
  124. // (01) 设置前一个节点为null
  125. // (02) 设置当前节点的内容为null
  126. // (03) 设置后一个节点为“新的当前节点”
  127. while (e != header) {
  128. Entry<E> next = e.next;
  129. e.next = e.previous = null;
  130. e.element = null;
  131. e = next;
  132. }
  133. header.next = header.previous = header;
  134. // 设置大小为0
  135. size = 0;
  136. modCount++;
  137. }
  138. // 返回LinkedList指定位置的元素
  139. public E get(int index) {
  140. return entry(index).element;
  141. }
  142. // 设置index位置对应的节点的值为element
  143. public E set(int index, E element) {
  144. Entry<E> e = entry(index);
  145. E oldVal = e.element;
  146. e.element = element;
  147. return oldVal;
  148. }
  149. // 在index前添加节点,且节点的值为element
  150. public void add(int index, E element) {
  151. addBefore(element, (index==size ? header : entry(index)));
  152. }
  153. // 删除index位置的节点
  154. public E remove(int index) {
  155. return remove(entry(index));
  156. }
  157. // 获取双向链表中指定位置的节点
  158. private Entry<E> entry(int index) {
  159. if (index < 0 || index >= size)
  160. throw new IndexOutOfBoundsException("Index: "+index+
  161. ", Size: "+size);
  162. Entry<E> e = header;
  163. // 获取index处的节点。
  164. // 若index < 双向链表长度的1/2,则从前先后查找;
  165. // 否则,从后向前查找。
  166. if (index < (size >> 1)) {
  167. for (int i = 0; i <= index; i++)
  168. e = e.next;
  169. } else {
  170. for (int i = size; i > index; i--)
  171. e = e.previous;
  172. }
  173. return e;
  174. }
  175. // 从前向后查找,返回“值为对象(o)的节点对应的索引”
  176. // 不存在就返回-1
  177. public int indexOf(Object o) {
  178. int index = 0;
  179. if (o==null) {
  180. for (Entry e = header.next; e != header; e = e.next) {
  181. if (e.element==null)
  182. return index;
  183. index++;
  184. }
  185. } else {
  186. for (Entry e = header.next; e != header; e = e.next) {
  187. if (o.equals(e.element))
  188. return index;
  189. index++;
  190. }
  191. }
  192. return -1;
  193. }
  194. // 从后向前查找,返回“值为对象(o)的节点对应的索引”
  195. // 不存在就返回-1
  196. public int lastIndexOf(Object o) {
  197. int index = size;
  198. if (o==null) {
  199. for (Entry e = header.previous; e != header; e = e.previous) {
  200. index--;
  201. if (e.element==null)
  202. return index;
  203. }
  204. } else {
  205. for (Entry e = header.previous; e != header; e = e.previous) {
  206. index--;
  207. if (o.equals(e.element))
  208. return index;
  209. }
  210. }
  211. return -1;
  212. }
  213. // 返回第一个节点
  214. // 若LinkedList的大小为0,则返回null
  215. public E peek() {
  216. if (size==0)
  217. return null;
  218. return getFirst();
  219. }
  220. // 返回第一个节点
  221. // 若LinkedList的大小为0,则抛出异常
  222. public E element() {
  223. return getFirst();
  224. }
  225. // 删除并返回第一个节点
  226. // 若LinkedList的大小为0,则返回null
  227. public E poll() {
  228. if (size==0)
  229. return null;
  230. return removeFirst();
  231. }
  232. // 将e添加双向链表末尾
  233. public boolean offer(E e) {
  234. return add(e);
  235. }
  236. // 将e添加双向链表开头
  237. public boolean offerFirst(E e) {
  238. addFirst(e);
  239. return true;
  240. }
  241. // 将e添加双向链表末尾
  242. public boolean offerLast(E e) {
  243. addLast(e);
  244. return true;
  245. }
  246. // 返回第一个节点
  247. // 若LinkedList的大小为0,则返回null
  248. public E peekFirst() {
  249. if (size==0)
  250. return null;
  251. return getFirst();
  252. }
  253. // 返回最后一个节点
  254. // 若LinkedList的大小为0,则返回null
  255. public E peekLast() {
  256. if (size==0)
  257. return null;
  258. return getLast();
  259. }
  260. // 删除并返回第一个节点
  261. // 若LinkedList的大小为0,则返回null
  262. public E pollFirst() {
  263. if (size==0)
  264. return null;
  265. return removeFirst();
  266. }
  267. // 删除并返回最后一个节点
  268. // 若LinkedList的大小为0,则返回null
  269. public E pollLast() {
  270. if (size==0)
  271. return null;
  272. return removeLast();
  273. }
  274. // 将e插入到双向链表开头
  275. public void push(E e) {
  276. addFirst(e);
  277. }
  278. // 删除并返回第一个节点
  279. public E pop() {
  280. return removeFirst();
  281. }
  282. // 从LinkedList开始向后查找,删除第一个值为元素(o)的节点
  283. // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
  284. public boolean removeFirstOccurrence(Object o) {
  285. return remove(o);
  286. }
  287. // 从LinkedList末尾向前查找,删除第一个值为元素(o)的节点
  288. // 从链表开始查找,如存在节点的值为元素(o)的节点,则删除该节点
  289. public boolean removeLastOccurrence(Object o) {
  290. if (o==null) {
  291. for (Entry<E> e = header.previous; e != header; e = e.previous) {
  292. if (e.element==null) {
  293. remove(e);
  294. return true;
  295. }
  296. }
  297. } else {
  298. for (Entry<E> e = header.previous; e != header; e = e.previous) {
  299. if (o.equals(e.element)) {
  300. remove(e);
  301. return true;
  302. }
  303. }
  304. }
  305. return false;
  306. }
  307. // 返回“index到末尾的全部节点”对应的ListIterator对象(List迭代器)
  308. public ListIterator<E> listIterator(int index) {
  309. return new ListItr(index);
  310. }
  311. // List迭代器
  312. private class ListItr implements ListIterator<E> {
  313. // 上一次返回的节点
  314. private Entry<E> lastReturned = header;
  315. // 下一个节点
  316. private Entry<E> next;
  317. // 下一个节点对应的索引值
  318. private int nextIndex;
  319. // 期望的改变计数。用来实现fail-fast机制。
  320. private int expectedModCount = modCount;
  321. // 构造函数。
  322. // 从index位置开始进行迭代
  323. ListItr(int index) {
  324. // index的有效性处理
  325. if (index < 0 || index > size)
  326. throw new IndexOutOfBoundsException("Index: "+index+ ", Size: "+size);
  327. // 若 “index 小于 ‘双向链表长度的一半’”,则从第一个元素开始往后查找;
  328. // 否则,从最后一个元素往前查找。
  329. if (index < (size >> 1)) {
  330. next = header.next;
  331. for (nextIndex=0; nextIndex<index; nextIndex++)
  332. next = next.next;
  333. } else {
  334. next = header;
  335. for (nextIndex=size; nextIndex>index; nextIndex--)
  336. next = next.previous;
  337. }
  338. }
  339. // 是否存在下一个元素
  340. public boolean hasNext() {
  341. // 通过元素索引是否等于“双向链表大小”来判断是否达到最后。
  342. return nextIndex != size;
  343. }
  344. // 获取下一个元素
  345. public E next() {
  346. checkForComodification();
  347. if (nextIndex == size)
  348. throw new NoSuchElementException();
  349. lastReturned = next;
  350. // next指向链表的下一个元素
  351. next = next.next;
  352. nextIndex++;
  353. return lastReturned.element;
  354. }
  355. // 是否存在上一个元素
  356. public boolean hasPrevious() {
  357. // 通过元素索引是否等于0,来判断是否达到开头。
  358. return nextIndex != 0;
  359. }
  360. // 获取上一个元素
  361. public E previous() {
  362. if (nextIndex == 0)
  363. throw new NoSuchElementException();
  364. // next指向链表的上一个元素
  365. lastReturned = next = next.previous;
  366. nextIndex--;
  367. checkForComodification();
  368. return lastReturned.element;
  369. }
  370. // 获取下一个元素的索引
  371. public int nextIndex() {
  372. return nextIndex;
  373. }
  374. // 获取上一个元素的索引
  375. public int previousIndex() {
  376. return nextIndex-1;
  377. }
  378. // 删除当前元素。
  379. // 删除双向链表中的当前节点
  380. public void remove() {
  381. checkForComodification();
  382. Entry<E> lastNext = lastReturned.next;
  383. try {
  384. LinkedList.this.remove(lastReturned);
  385. } catch (NoSuchElementException e) {
  386. throw new IllegalStateException();
  387. }
  388. if (next==lastReturned)
  389. next = lastNext;
  390. else
  391. nextIndex--;
  392. lastReturned = header;
  393. expectedModCount++;
  394. }
  395. // 设置当前节点为e
  396. public void set(E e) {
  397. if (lastReturned == header)
  398. throw new IllegalStateException();
  399. checkForComodification();
  400. lastReturned.element = e;
  401. }
  402. // 将e添加到当前节点的前面
  403. public void add(E e) {
  404. checkForComodification();
  405. lastReturned = header;
  406. addBefore(e, next);
  407. nextIndex++;
  408. expectedModCount++;
  409. }
  410. // 判断 “modCount和expectedModCount是否相等”,依次来实现fail-fast机制。
  411. final void checkForComodification() {
  412. if (modCount != expectedModCount)
  413. throw new ConcurrentModificationException();
  414. }
  415. }
  416. // 双向链表的节点所对应的数据结构。
  417. // 包含3部分:上一节点,下一节点,当前节点值。
  418. private static class Entry<E> {
  419. // 当前节点所包含的值
  420. E element;
  421. // 下一个节点
  422. Entry<E> next;
  423. // 上一个节点
  424. Entry<E> previous;
  425. /**
  426. * 链表节点的构造函数。
  427. * 参数说明:
  428. * element —— 节点所包含的数据
  429. * next —— 下一个节点
  430. * previous —— 上一个节点
  431. */
  432. Entry(E element, Entry<E> next, Entry<E> previous) {
  433. this.element = element;
  434. this.next = next;
  435. this.previous = previous;
  436. }
  437. }
  438. // 将节点(节点数据是e)添加到entry节点之前。
  439. private Entry<E> addBefore(E e, Entry<E> entry) {
  440. // 新建节点newEntry,将newEntry插入到节点e之前;并且设置newEntry的数据是e
  441. Entry<E> newEntry = new Entry<E>(e, entry, entry.previous);
  442. newEntry.previous.next = newEntry;
  443. newEntry.next.previous = newEntry;
  444. // 修改LinkedList大小
  445. size++;
  446. // 修改LinkedList的修改统计数:用来实现fail-fast机制。
  447. modCount++;
  448. return newEntry;
  449. }
  450. // 将节点从链表中删除
  451. private E remove(Entry<E> e) {
  452. if (e == header)
  453. throw new NoSuchElementException();
  454. E result = e.element;
  455. e.previous.next = e.next;
  456. e.next.previous = e.previous;
  457. e.next = e.previous = null;
  458. e.element = null;
  459. size--;
  460. modCount++;
  461. return result;
  462. }
  463. // 反向迭代器
  464. public Iterator<E> descendingIterator() {
  465. return new DescendingIterator();
  466. }
  467. // 反向迭代器实现类。
  468. private class DescendingIterator implements Iterator {
  469. final ListItr itr = new ListItr(size());
  470. // 反向迭代器是否下一个元素。
  471. // 实际上是判断双向链表的当前节点是否达到开头
  472. public boolean hasNext() {
  473. return itr.hasPrevious();
  474. }
  475. // 反向迭代器获取下一个元素。
  476. // 实际上是获取双向链表的前一个节点
  477. public E next() {
  478. return itr.previous();
  479. }
  480. // 删除当前节点
  481. public void remove() {
  482. itr.remove();
  483. }
  484. }
  485. // 返回LinkedList的Object[]数组
  486. public Object[] toArray() {
  487. // 新建Object[]数组
  488. Object[] result = new Object[size];
  489. int i = 0;
  490. // 将链表中所有节点的数据都添加到Object[]数组中
  491. for (Entry<E> e = header.next; e != header; e = e.next)
  492. result[i++] = e.element;
  493. return result;
  494. }
  495. // 返回LinkedList的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  496. public <T> T[] toArray(T[] a) {
  497. // 若数组a的大小 < LinkedList的元素个数(意味着数组a不能容纳LinkedList中全部元素)
  498. // 则新建一个T[]数组,T[]的大小为LinkedList大小,并将该T[]赋值给a。
  499. if (a.length < size)
  500. a = (T[])java.lang.reflect.Array.newInstance(
  501. a.getClass().getComponentType(), size);
  502. // 将链表中所有节点的数据都添加到数组a中
  503. int i = 0;
  504. Object[] result = a;
  505. for (Entry<E> e = header.next; e != header; e = e.next)
  506. result[i++] = e.element;
  507. if (a.length > size)
  508. a[size] = null;
  509. return a;
  510. }
  511. // 克隆函数。返回LinkedList的克隆对象。
  512. public Object clone() {
  513. LinkedList<E> clone = null;
  514. // 克隆一个LinkedList克隆对象
  515. try {
  516. clone = (LinkedList<E>) super.clone();
  517. } catch (CloneNotSupportedException e) {
  518. throw new InternalError();
  519. }
  520. // 新建LinkedList表头节点
  521. clone.header = new Entry<E>(null, null, null);
  522. clone.header.next = clone.header.previous = clone.header;
  523. clone.size = 0;
  524. clone.modCount = 0;
  525. // 将链表中所有节点的数据都添加到克隆对象中
  526. for (Entry<E> e = header.next; e != header; e = e.next)
  527. clone.add(e.element);
  528. return clone;
  529. }
  530. // java.io.Serializable的写入函数
  531. // 将LinkedList的“容量,所有的元素值”都写入到输出流中
  532. private void writeObject(java.io.ObjectOutputStream s)
  533. throws java.io.IOException {
  534. // Write out any hidden serialization magic
  535. s.defaultWriteObject();
  536. // 写入“容量”
  537. s.writeInt(size);
  538. // 将链表中所有节点的数据都写入到输出流中
  539. for (Entry e = header.next; e != header; e = e.next)
  540. s.writeObject(e.element);
  541. }
  542. // java.io.Serializable的读取函数:根据写入方式反向读出
  543. // 先将LinkedList的“容量”读出,然后将“所有的元素值”读出
  544. private void readObject(java.io.ObjectInputStream s)
  545. throws java.io.IOException, ClassNotFoundException {
  546. // Read in any hidden serialization magic
  547. s.defaultReadObject();
  548. // 从输入流中读取“容量”
  549. int size = s.readInt();
  550. // 新建链表表头节点
  551. header = new Entry<E>(null, null, null);
  552. header.next = header.previous = header;
  553. // 从输入流中将“所有的元素值”并逐个添加到链表中
  554. for (int i=0; i<size; i++)
  555. addBefore((E)s.readObject(), header);
  556. }
  557. }

总结一下:
(1) LinkedList 实际上是通过双向链表去实现的。
它包含一个非常重要的内部类:Entry。Entry是双向链表节点所对应的数据结构,它包括的属性有:当前节点的值,上一个节点,下一个节点。
(2) 从LinkedList的实现方式中可以发现,它不存在LinkedList容量不足的问题。
(3) LinkedList的克隆函数,即是将全部元素克隆到一个新的LinkedList对象中。
(4) LinkedList实现了java.io.Serializable。当写入到输出流时,先写入“容量”,再依次写入“每一个节点保护的值”;当读出输入流时,先读取“容量”,再依次读取“每一个元素”。
(5) 由于LinkedList实现了Deque,而Deque接口定义了在双端队列两端访问元素的方法。提供插入、移除和检查元素的方法。每种方法都存在两种形式:一种形式在操作失败时抛出异常,另一种形式返回一个特殊值(null 或 false,具体取决于操作)。

  1. 第一个元素(头部) 最后一个元素(尾部)
  2. 抛出异常 特殊值 抛出异常 特殊值
  3. 插入 addFirst(e) offerFirst(e) addLast(e) offerLast(e)
  4. 移除 removeFirst() pollFirst() removeLast() pollLast()
  5. 检查 getFirst() peekFirst() getLast() peekLast()

LinkedList可以作为FIFO(先进先出)的队列,作为FIFO的队列时,下表的方法等价:

  1. 队列方法 等效方法
  2. add(e) addLast(e)
  3. offer(e) offerLast(e)
  4. remove() removeFirst()
  5. poll() pollFirst()
  6. element() getFirst()
  7. peek() peekFirst()

LinkedList可以作为LIFO(后进先出)的栈,作为LIFO的栈时,下表的方法等价:

  1. 栈方法 等效方法
  2. push(e) addFirst(e)
  3. pop() removeFirst()
  4. peek() peekFirst()

LinkedList的遍历方式

LinkedList支持多种遍历方式,建议不要采用随机访问的方式去遍历LinkedList,而采用逐个遍历的方式。
(1)通过迭代器遍历。即通过Iterator去遍历。

  1. for(Iterator iter = list.iterator(); iter.hasNext();)
  2. iter.next();

(2)通过快速随机访问遍历LinkedList

  1. int size = list.size();
  2. for (int i=0; i<size; i++) {
  3. list.get(i);
  4. }

(3)通过另外一种for循环来遍历LinkedList

  1. for (Integer integ:list) ;

(4)通过pollFirst()来遍历LinkedList

  1. while(list.pollFirst() != null) ;

(5)通过pollLast()来遍历LinkedList

  1. while(list.pollLast() != null);

(6)通过removeFirst()来遍历LinkedList

  1. try {
  2. while(list.removeFirst() != null);
  3. } catch (NoSuchElementException e) {
  4. }

(7)通过removeLast()来遍历LinkedList

  1. try {
  2. while(list.removeLast() != null);
  3. } catch (NoSuchElementException e) {
  4. }

Vector

简介

Vector 是矢量队列,它是JDK1.0版本添加的类。继承于AbstractList,实现了List, RandomAccess, Cloneable这些接口。
Vector 继承了AbstractList,实现了List;所以,它是一个队列,支持相关的添加、删除、修改、遍历等功能。
Vector 实现了RandmoAccess接口,即提供了随机访问功能。RandmoAccess是java中用来被List实现,为List提供快速访问功能的。在Vector中,我们即可以通过元素的序号快速获取元素对象;这就是快速随机访问。
Vector 实现了Cloneable接口,即实现clone()函数。它能被克隆。

和ArrayList不同,Vector中的操作是线程安全的。

Vector的构造函数

  1. //Vector共有4个构造函数
  2. // 默认构造函数
  3. Vector()
  4. // capacity是Vector的默认容量大小。当由于增加数据导致容量增加时,每次容量会增加一倍。
  5. Vector(int capacity)
  6. // capacity是Vector的默认容量大小,capacityIncrement是每次Vector容量增加时的增量值。
  7. Vector(int capacity, int capacityIncrement)
  8. // 创建一个包含collection的Vector
  9. Vector(Collection<? extends E> collection)

Vector的API

  1. package java.util;
  2. public class Vector<E>
  3. extends AbstractList<E>
  4. implements List<E>, RandomAccess, Cloneable, java.io.Serializable
  5. {
  6. // 保存Vector中数据的数组
  7. protected Object[] elementData;
  8. // 实际数据的数量
  9. protected int elementCount;
  10. // 容量增长系数
  11. protected int capacityIncrement;
  12. // Vector的序列版本号
  13. private static final long serialVersionUID = -2767605614048989439L;
  14. // Vector构造函数。默认容量是10。
  15. public Vector() {
  16. this(10);
  17. }
  18. // 指定Vector容量大小的构造函数
  19. public Vector(int initialCapacity) {
  20. this(initialCapacity, 0);
  21. }
  22. // 指定Vector"容量大小"和"增长系数"的构造函数
  23. public Vector(int initialCapacity, int capacityIncrement) {
  24. super();
  25. if (initialCapacity < 0)
  26. throw new IllegalArgumentException("Illegal Capacity: "+
  27. initialCapacity);
  28. // 新建一个数组,数组容量是initialCapacity
  29. this.elementData = new Object[initialCapacity];
  30. // 设置容量增长系数
  31. this.capacityIncrement = capacityIncrement;
  32. }
  33. // 指定集合的Vector构造函数。
  34. public Vector(Collection<? extends E> c) {
  35. // 获取“集合(c)”的数组,并将其赋值给elementData
  36. elementData = c.toArray();
  37. // 设置数组长度
  38. elementCount = elementData.length;
  39. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  40. if (elementData.getClass() != Object[].class)
  41. elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
  42. }
  43. // 将数组Vector的全部元素都拷贝到数组anArray中
  44. public synchronized void copyInto(Object[] anArray) {
  45. System.arraycopy(elementData, 0, anArray, 0, elementCount);
  46. }
  47. // 将当前容量值设为 =实际元素个数
  48. public synchronized void trimToSize() {
  49. modCount++;
  50. int oldCapacity = elementData.length;
  51. if (elementCount < oldCapacity) {
  52. elementData = Arrays.copyOf(elementData, elementCount);
  53. }
  54. }
  55. // 确认“Vector容量”的帮助函数
  56. private void ensureCapacityHelper(int minCapacity) {
  57. int oldCapacity = elementData.length;
  58. // 当Vector的容量不足以容纳当前的全部元素,增加容量大小。
  59. // 若 容量增量系数>0(即capacityIncrement>0),则将容量增大当capacityIncrement
  60. // 否则,将容量增大一倍。
  61. if (minCapacity > oldCapacity) {
  62. Object[] oldData = elementData;
  63. int newCapacity = (capacityIncrement > 0) ?
  64. (oldCapacity + capacityIncrement) : (oldCapacity * 2);
  65. if (newCapacity < minCapacity) {
  66. newCapacity = minCapacity;
  67. }
  68. elementData = Arrays.copyOf(elementData, newCapacity);
  69. }
  70. }
  71. // 确定Vector的容量。
  72. public synchronized void ensureCapacity(int minCapacity) {
  73. // 将Vector的改变统计数+1
  74. modCount++;
  75. ensureCapacityHelper(minCapacity);
  76. }
  77. // 设置容量值为 newSize
  78. public synchronized void setSize(int newSize) {
  79. modCount++;
  80. if (newSize > elementCount) {
  81. // 若 "newSize 大于 Vector容量",则调整Vector的大小。
  82. ensureCapacityHelper(newSize);
  83. } else {
  84. // 若 "newSize 小于/等于 Vector容量",则将newSize位置开始的元素都设置为null
  85. for (int i = newSize ; i < elementCount ; i++) {
  86. elementData[i] = null;
  87. }
  88. }
  89. elementCount = newSize;
  90. }
  91. // 返回“Vector的总的容量”
  92. public synchronized int capacity() {
  93. return elementData.length;
  94. }
  95. // 返回“Vector的实际大小”,即Vector中元素个数
  96. public synchronized int size() {
  97. return elementCount;
  98. }
  99. // 判断Vector是否为空
  100. public synchronized boolean isEmpty() {
  101. return elementCount == 0;
  102. }
  103. // 返回“Vector中全部元素对应的Enumeration”
  104. public Enumeration<E> elements() {
  105. // 通过匿名类实现Enumeration
  106. return new Enumeration<E>() {
  107. int count = 0;
  108. // 是否存在下一个元素
  109. public boolean hasMoreElements() {
  110. return count < elementCount;
  111. }
  112. // 获取下一个元素
  113. public E nextElement() {
  114. synchronized (Vector.this) {
  115. if (count < elementCount) {
  116. return (E)elementData[count++];
  117. }
  118. }
  119. throw new NoSuchElementException("Vector Enumeration");
  120. }
  121. };
  122. }
  123. // 返回Vector中是否包含对象(o)
  124. public boolean contains(Object o) {
  125. return indexOf(o, 0) >= 0;
  126. }
  127. // 从index位置开始向后查找元素(o)。
  128. // 若找到,则返回元素的索引值;否则,返回-1
  129. public synchronized int indexOf(Object o, int index) {
  130. if (o == null) {
  131. // 若查找元素为null,则正向找出null元素,并返回它对应的序号
  132. for (int i = index ; i < elementCount ; i++)
  133. if (elementData[i]==null)
  134. return i;
  135. } else {
  136. // 若查找元素不为null,则正向找出该元素,并返回它对应的序号
  137. for (int i = index ; i < elementCount ; i++)
  138. if (o.equals(elementData[i]))
  139. return i;
  140. }
  141. return -1;
  142. }
  143. // 查找并返回元素(o)在Vector中的索引值
  144. public int indexOf(Object o) {
  145. return indexOf(o, 0);
  146. }
  147. // 从后向前查找元素(o)。并返回元素的索引
  148. public synchronized int lastIndexOf(Object o) {
  149. return lastIndexOf(o, elementCount-1);
  150. }
  151. // 从后向前查找元素(o)。开始位置是从前向后的第index个数;
  152. // 若找到,则返回元素的“索引值”;否则,返回-1。
  153. public synchronized int lastIndexOf(Object o, int index) {
  154. if (index >= elementCount)
  155. throw new IndexOutOfBoundsException(index + " >= "+ elementCount);
  156. if (o == null) {
  157. // 若查找元素为null,则反向找出null元素,并返回它对应的序号
  158. for (int i = index; i >= 0; i--)
  159. if (elementData[i]==null)
  160. return i;
  161. } else {
  162. // 若查找元素不为null,则反向找出该元素,并返回它对应的序号
  163. for (int i = index; i >= 0; i--)
  164. if (o.equals(elementData[i]))
  165. return i;
  166. }
  167. return -1;
  168. }
  169. // 返回Vector中index位置的元素。
  170. // 若index月结,则抛出异常
  171. public synchronized E elementAt(int index) {
  172. if (index >= elementCount) {
  173. throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
  174. }
  175. return (E)elementData[index];
  176. }
  177. // 获取Vector中的第一个元素。
  178. // 若失败,则抛出异常!
  179. public synchronized E firstElement() {
  180. if (elementCount == 0) {
  181. throw new NoSuchElementException();
  182. }
  183. return (E)elementData[0];
  184. }
  185. // 获取Vector中的最后一个元素。
  186. // 若失败,则抛出异常!
  187. public synchronized E lastElement() {
  188. if (elementCount == 0) {
  189. throw new NoSuchElementException();
  190. }
  191. return (E)elementData[elementCount - 1];
  192. }
  193. // 设置index位置的元素值为obj
  194. public synchronized void setElementAt(E obj, int index) {
  195. if (index >= elementCount) {
  196. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  197. elementCount);
  198. }
  199. elementData[index] = obj;
  200. }
  201. // 删除index位置的元素
  202. public synchronized void removeElementAt(int index) {
  203. modCount++;
  204. if (index >= elementCount) {
  205. throw new ArrayIndexOutOfBoundsException(index + " >= " +
  206. elementCount);
  207. } else if (index < 0) {
  208. throw new ArrayIndexOutOfBoundsException(index);
  209. }
  210. int j = elementCount - index - 1;
  211. if (j > 0) {
  212. System.arraycopy(elementData, index + 1, elementData, index, j);
  213. }
  214. elementCount--;
  215. elementData[elementCount] = null; /* to let gc do its work */
  216. }
  217. // 在index位置处插入元素(obj)
  218. public synchronized void insertElementAt(E obj, int index) {
  219. modCount++;
  220. if (index > elementCount) {
  221. throw new ArrayIndexOutOfBoundsException(index
  222. + " > " + elementCount);
  223. }
  224. ensureCapacityHelper(elementCount + 1);
  225. System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
  226. elementData[index] = obj;
  227. elementCount++;
  228. }
  229. // 将“元素obj”添加到Vector末尾
  230. public synchronized void addElement(E obj) {
  231. modCount++;
  232. ensureCapacityHelper(elementCount + 1);
  233. elementData[elementCount++] = obj;
  234. }
  235. // 在Vector中查找并删除元素obj。
  236. // 成功的话,返回true;否则,返回false。
  237. public synchronized boolean removeElement(Object obj) {
  238. modCount++;
  239. int i = indexOf(obj);
  240. if (i >= 0) {
  241. removeElementAt(i);
  242. return true;
  243. }
  244. return false;
  245. }
  246. // 删除Vector中的全部元素
  247. public synchronized void removeAllElements() {
  248. modCount++;
  249. // 将Vector中的全部元素设为null
  250. for (int i = 0; i < elementCount; i++)
  251. elementData[i] = null;
  252. elementCount = 0;
  253. }
  254. // 克隆函数
  255. public synchronized Object clone() {
  256. try {
  257. Vector<E> v = (Vector<E>) super.clone();
  258. // 将当前Vector的全部元素拷贝到v中
  259. v.elementData = Arrays.copyOf(elementData, elementCount);
  260. v.modCount = 0;
  261. return v;
  262. } catch (CloneNotSupportedException e) {
  263. // this shouldn't happen, since we are Cloneable
  264. throw new InternalError();
  265. }
  266. }
  267. // 返回Object数组
  268. public synchronized Object[] toArray() {
  269. return Arrays.copyOf(elementData, elementCount);
  270. }
  271. // 返回Vector的模板数组。所谓模板数组,即可以将T设为任意的数据类型
  272. public synchronized <T> T[] toArray(T[] a) {
  273. // 若数组a的大小 < Vector的元素个数;
  274. // 则新建一个T[]数组,数组大小是“Vector的元素个数”,并将“Vector”全部拷贝到新数组中
  275. if (a.length < elementCount)
  276. return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass());
  277. // 若数组a的大小 >= Vector的元素个数;
  278. // 则将Vector的全部元素都拷贝到数组a中。
  279. System.arraycopy(elementData, 0, a, 0, elementCount);
  280. if (a.length > elementCount)
  281. a[elementCount] = null;
  282. return a;
  283. }
  284. // 获取index位置的元素
  285. public synchronized E get(int index) {
  286. if (index >= elementCount)
  287. throw new ArrayIndexOutOfBoundsException(index);
  288. return (E)elementData[index];
  289. }
  290. // 设置index位置的值为element。并返回index位置的原始值
  291. public synchronized E set(int index, E element) {
  292. if (index >= elementCount)
  293. throw new ArrayIndexOutOfBoundsException(index);
  294. Object oldValue = elementData[index];
  295. elementData[index] = element;
  296. return (E)oldValue;
  297. }
  298. // 将“元素e”添加到Vector最后。
  299. public synchronized boolean add(E e) {
  300. modCount++;
  301. ensureCapacityHelper(elementCount + 1);
  302. elementData[elementCount++] = e;
  303. return true;
  304. }
  305. // 删除Vector中的元素o
  306. public boolean remove(Object o) {
  307. return removeElement(o);
  308. }
  309. // 在index位置添加元素element
  310. public void add(int index, E element) {
  311. insertElementAt(element, index);
  312. }
  313. // 删除index位置的元素,并返回index位置的原始值
  314. public synchronized E remove(int index) {
  315. modCount++;
  316. if (index >= elementCount)
  317. throw new ArrayIndexOutOfBoundsException(index);
  318. Object oldValue = elementData[index];
  319. int numMoved = elementCount - index - 1;
  320. if (numMoved > 0)
  321. System.arraycopy(elementData, index+1, elementData, index,
  322. numMoved);
  323. elementData[--elementCount] = null; // Let gc do its work
  324. return (E)oldValue;
  325. }
  326. // 清空Vector
  327. public void clear() {
  328. removeAllElements();
  329. }
  330. // 返回Vector是否包含集合c
  331. public synchronized boolean containsAll(Collection<?> c) {
  332. return super.containsAll(c);
  333. }
  334. // 将集合c添加到Vector中
  335. public synchronized boolean addAll(Collection<? extends E> c) {
  336. modCount++;
  337. Object[] a = c.toArray();
  338. int numNew = a.length;
  339. ensureCapacityHelper(elementCount + numNew);
  340. // 将集合c的全部元素拷贝到数组elementData中
  341. System.arraycopy(a, 0, elementData, elementCount, numNew);
  342. elementCount += numNew;
  343. return numNew != 0;
  344. }
  345. // 删除集合c的全部元素
  346. public synchronized boolean removeAll(Collection<?> c) {
  347. return super.removeAll(c);
  348. }
  349. // 删除“非集合c中的元素”
  350. public synchronized boolean retainAll(Collection<?> c) {
  351. return super.retainAll(c);
  352. }
  353. // 从index位置开始,将集合c添加到Vector中
  354. public synchronized boolean addAll(int index, Collection<? extends E> c) {
  355. modCount++;
  356. if (index < 0 || index > elementCount)
  357. throw new ArrayIndexOutOfBoundsException(index);
  358. Object[] a = c.toArray();
  359. int numNew = a.length;
  360. ensureCapacityHelper(elementCount + numNew);
  361. int numMoved = elementCount - index;
  362. if (numMoved > 0)
  363. System.arraycopy(elementData, index, elementData, index + numNew, numMoved);
  364. System.arraycopy(a, 0, elementData, index, numNew);
  365. elementCount += numNew;
  366. return numNew != 0;
  367. }
  368. // 返回两个对象是否相等
  369. public synchronized boolean equals(Object o) {
  370. return super.equals(o);
  371. }
  372. // 计算哈希值
  373. public synchronized int hashCode() {
  374. return super.hashCode();
  375. }
  376. // 调用父类的toString()
  377. public synchronized String toString() {
  378. return super.toString();
  379. }
  380. // 获取Vector中fromIndex(包括)到toIndex(不包括)的子集
  381. public synchronized List<E> subList(int fromIndex, int toIndex) {
  382. return Collections.synchronizedList(super.subList(fromIndex, toIndex), this);
  383. }
  384. // 删除Vector中fromIndex到toIndex的元素
  385. protected synchronized void removeRange(int fromIndex, int toIndex) {
  386. modCount++;
  387. int numMoved = elementCount - toIndex;
  388. System.arraycopy(elementData, toIndex, elementData, fromIndex,
  389. numMoved);
  390. // Let gc do its work
  391. int newElementCount = elementCount - (toIndex-fromIndex);
  392. while (elementCount != newElementCount)
  393. elementData[--elementCount] = null;
  394. }
  395. // java.io.Serializable的写入函数
  396. private synchronized void writeObject(java.io.ObjectOutputStream s)
  397. throws java.io.IOException {
  398. s.defaultWriteObject();
  399. }
  400. }

Vector继承关系

  1. java.lang.Object
  2. java.util.AbstractCollection<E>
  3. java.util.AbstractList<E>
  4. java.util.Vector<E>
  5. public class Vector<E>
  6. extends AbstractList<E>
  7. implements List<E>, RandomAccess, Cloneable, java.io.Serializable {
  8. }

继承关系图

Vector的数据结构和ArrayList差不多,它包含了3个成员变量:elementData , elementCount, capacityIncrement。

(1) elementData 是”Object[]类型的数组”,它保存了添加到Vector中的元素。elementData是个动态数组,如果初始化Vector时,没指定动态数组的>大小,则使用默认大小10。随着Vector中元素的增加,Vector的容量也会动态增长,capacityIncrement是与容量增长相关的增长系数,具体的增长方式,请参考源码分析中的ensureCapacity()函数。

(2) elementCount 是动态数组的实际大小。

(3) capacityIncrement 是动态数组的增长系数。如果在创建Vector时,指定了capacityIncrement的大小;则,每次当Vector中动态数组容量增加时,增加的大小都是capacityIncrement。

(4) Vector实际上是通过一个数组去保存数据的。当我们构造Vecotr时;若使用默认构造函数,则Vector的默认容量大小是10。

(5) 当Vector容量不足以容纳全部元素时,Vector的容量会增加。若容量增加系数 >0,则将容量的值增加“容量增加系数”;否则,将容量大小增加一倍。

(6) Vector的克隆函数,即是将全部元素克隆到一个数组中。

遍历方式

通过Iterator去遍历

  1. for(Iterator iter = vec.iterator(); iter.hasNext();)
  2. iter.next();

通过索引值去遍历

  1. Integer value = null;
  2. int size = vec.size();
  3. for (int i=0; i<size; i++) {
  4. value = (Integer)vec.get(i);
  5. }

for循环

  1. Integer value = null;
  2. for (Integer integ:vec) {
  3. value = integ;
  4. }

Enumeration遍历

  1. Integer value = null;
  2. Enumeration enu = vec.elements();
  3. while (enu.hasMoreElements()) {
  4. value = (Integer)enu.nextElement();
  5. }

总结:遍历Vector,使用索引的随机访问方式最快,使用迭代器最慢。

Stack

简介

Stack是栈。它的特性是:先进后出(FILO, First In Last Out)。
java工具包中的Stack是继承于Vector(矢量队列)的,由于Vector是通过数组实现的,这就意味着,Stack也是通过数组实现的,而非链表。当然,我们也可以将LinkedList当作栈来使用!已经详细介绍过Vector的数据结构,这里就不再对Stack的数据结构进行说明了。

继承关系

  1. java.lang.Object
  2. java.util.AbstractCollection<E>
  3. java.util.AbstractList<E>
  4. java.util.Vector<E>
  5. java.util.Stack<E>
  6. public class Stack<E> extends Vector<E> {
  7. }

这里写图片描述

构造函数

只有一个默认的而构造函数

  1. Stack()

Stack源码解析

  1. package java.util;
  2. public
  3. class Stack<E> extends Vector<E> {
  4. // 版本ID。这个用于版本升级控制,这里不须理会!
  5. private static final long serialVersionUID = 1224463164541339165L;
  6. // 构造函数
  7. public Stack() {
  8. }
  9. // push函数:将元素存入栈顶
  10. public E push(E item) {
  11. // 将元素存入栈顶。
  12. // addElement()的实现在Vector.java中
  13. addElement(item);
  14. return item;
  15. }
  16. // pop函数:返回栈顶元素,并将其从栈中删除
  17. public synchronized E pop() {
  18. E obj;
  19. int len = size();
  20. obj = peek();
  21. // 删除栈顶元素,removeElementAt()的实现在Vector.java中
  22. removeElementAt(len - 1);
  23. return obj;
  24. }
  25. // peek函数:返回栈顶元素,不执行删除操作
  26. public synchronized E peek() {
  27. int len = size();
  28. if (len == 0)
  29. throw new EmptyStackException();
  30. // 返回栈顶元素,elementAt()具体实现在Vector.java中
  31. return elementAt(len - 1);
  32. }
  33. // 栈是否为空
  34. public boolean empty() {
  35. return size() == 0;
  36. }
  37. // 查找“元素o”在栈中的位置:由栈底向栈顶方向数
  38. public synchronized int search(Object o) {
  39. // 获取元素索引,elementAt()具体实现在Vector.java中
  40. int i = lastIndexOf(o);
  41. if (i >= 0) {
  42. return size() - i;
  43. }
  44. return -1;
  45. }
  46. }

(1) Stack实际上也是通过数组去实现的。
执行push时(即,将元素推入栈中),是通过将元素追加的数组的末尾中。
执行peek时(即,取出栈顶元素,不执行删除),是返回数组末尾的元素。
执行pop时(即,取出栈顶元素,并将该元素从栈中删除),是取出数组末尾的元素,然后将该元素从数组中删除。
(2) Stack继承于Vector,意味着Vector拥有的属性和功能,Stack都拥有。
参考1
参考2

发表评论

表情:
评论列表 (有 0 条评论,277人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Java集合之一—HashMap

    > 哈希表(hash table) > 也叫散列表,是一种非常重要的数据结构,应用场景及其丰富,许多缓存技术(比如memcached)的核心其实就是在内存中维护一张大的哈希

    相关 Java集合之一集合简介

    开发中少不了对数据的存储操作,我们可以使用以下两种方式对数据进行存储。 ①数组          数组是在内存中连续存储数据,我们可以通过下标快速查找数据。数组适合元素个数

    相关 java技术--基础

    两年没碰了,先从基础的开始捡起来,今天的收获!19-24下次看吧。 1.面向对象的特征 抽象(这个不是)、封装、继承 、多态 抽象:把事物之间的相似和共性之处单独归为一个