至此;答应自己的事就一定要做到
今天看了下Vector的代码实现;以前看面试题或者论坛之类;就会经常看到一下ArrayList,LinkedList,Vectoe之间的比较,但是我个人在现在都感觉Vector使用的好少,但是今天还是看了下代码.
这里就可以看清楚的看出类之间的关系;
参数部分 :
// 存储数据的数组 protected Object[] elementData;
// 集合的大小 (可以这么理解)
protected int elementCount;
protected int capacityIncrement;
// 最大的长度 Integer.MAX_VALUE - 8
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
构成部分
// 无参 public Vector() { this(10); }
// 一个参数
public Vector(int initialCapacity) { this(initialCapacity, 0); }
// 二个参数
public Vector(int initialCapacity, int capacityIncrement) { super(); if (initialCapacity < 0) throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity); this.elementData = new Object[initialCapacity]; this.capacityIncrement = capacityIncrement; }
这里不难看出:最后走到了二个参数的构造里面.
对initialCapacity 进行是否小于0的判断;
如果不是小于0;测给elementData 声明为 initialCapacity 大
add,get等部分
关于 add ; get中掉用的方法;可以参考下 https://blog.csdn.net/by_yangge/article/details/100178699
大致的思想什么还是差不多的
public synchronized boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; }
public synchronized E set(int index, E element) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); elementData[index] = element; return oldValue; }
public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); }
public boolean remove(Object o) { return removeElement(o); }
public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; }
从这里可以不难看出来每个方法都加上了 synchronized ; 这个就是表示同步的意思.在多线程的情况下,每次都只有一个线程可以进这个方法,所以不难看出来Vector 比 ArrayList安全的地方,那就是Vector中的很多地方都是加上了 synchronized 同步。
存储的数据类型是和ArrayList 是一样的.