国内最全IT社区平台 联系我们 | 收藏本站
华晨云阿里云优惠2
您当前位置:首页 > php开源 > php教程 > Java源代码分析之Vector数组

Java源代码分析之Vector数组

来源:程序员人生   发布时间:2016-07-28 08:41:30 阅读次数:2089次

Vector源码分析

  • 每一个Java程序员应当的特性

    • 可变长数组(grow or shrink
    • 能够使用索引获得值(accessed using an integer index
    • 多线程环境下线程安全
  • 类图

package java.util; import java.util.function.Consumer; import java.util.function.Predicate; import java.util.function.UnaryOperator; /* vector 通过capacity(容量)和capacityIncrement(增量)两个属性来最化管理存储, capacity 1般都比 size 大。 当知道需要插入大量元素时,可以提早分配给vector较大空间,减少分配内存次数, 从而减少没必要要的开消。 此类的iterator和listIterator方法返回的迭代器是快速失败的:如果该向量在任什么时候间从结构上修改创建迭代器后, 以任何方式,除通过迭代器本身的remove或add方法,迭代器都将抛出ConcurrentModificationException。 因此,在并发的修改,迭代器很快就会完全失败,而不是在将来不肯定的时间任意冒险,不肯定性的行动。 通过elements方法返回的Enumeration不是快速失败的。 注意,迭代器的快速失败行动不能得到保证,由于它是,1般来讲, 不可能作出任何硬性保证不同步并发修改的存在。快速失败迭代器抛出ConcurrentModificationException尽最大努力的基础上。 因此,这将是毛病的编写1个程序,依赖于此异常为它的正确性: 迭代器的快速失败行动应当仅用于检测bug。 从Java 2平台v1.2,这个类是改进来实现List接口,使它成为Java Collections Framework的成员。 不同的是新的集合实现不同,Vector是同步的。 如果不需要线程安全履行,建议代替矢量的使用的ArrayList。 */ public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable { // 寄存数据的数组 protected Object[] elementData; // 实际元素个数 protected int elementCount; // 容量增量,每次扩容增加的大小,如果 capacityIncrement小雨或等于0,那末容量会每次翻倍double的增长 protected int capacityIncrement; private static final long serialVersionUID = -2767605614048989439L; // 数组的初始化,增量的初始化,容量小于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; } // 指定容量,并且增量为0,每次扩容方法为翻倍 public Vector(int initialCapacity) { this(initialCapacity, 0); } //默许构造方法,默许容量大小为10 public Vector() { this(10); } // 根据指定集合创建vector // 另外vector的顺序由集合Collection的iterator遍历的顺序来保证 public Vector(Collection<? extends E> c) { elementData = c.toArray(); // 根据集合生成数组,数组是reallocate的,不存在refer关系 elementCount = elementData.length; //下面1句话简单理解就是 toArray()返回的其实不1定是Object[]数组(实际类型) // 具体请看 我的博客文章 http://blog.csdn.net/huzhigenlaohu/article/details/51702737 // c.toArray might (incorrectly) not return Object[] (see 6260652) if (elementData.getClass() != Object[].class) elementData = Arrays.copyOf(elementData, elementCount, Object[].class); } /** * anArray 为空会报空指针异常 , anArray的长度不能容纳elementData所有元素汇会报索引越界异常 * 另外 c.toArray not return Object[]时候 报 ArrayStoreException * 请看 http://blog.csdn.net/huzhigenlaohu/article/details/51702737 */ public synchronized void copyInto(Object[] anArray) { System.arraycopy(elementData, 0, anArray, 0, elementCount); } // 去掉Vector 数组后面未存入数据的部份,使得Capacity(length) = elementCount public synchronized void trimToSize() { //这个 字段含义为 vector 结构(1般指的是大小)被修改的次数 modCount++; int oldCapacity = elementData.length; if (elementCount < oldCapacity) { elementData = Arrays.copyOf(elementData, elementCount); } } //扩容函数(对外暴露的函数,实现看grow) public synchronized void ensureCapacity(int minCapacity) { if (minCapacity > 0) { modCount++; ensureCapacityHelper(minCapacity); } } private void ensureCapacityHelper(int minCapacity) { // overflow-conscious code if (minCapacity - elementData.length > 0) grow(minCapacity); } private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; //这个才是看的重点,上面两个函数可以疏忽掉。。。额,说错了,不是疏忽掉而是可以不看 private void grow(int minCapacity) { // overflow-conscious code int oldCapacity = elementData.length; // 如果增量大于0那末是的容量+Increment,如果小于等于0,那末容量翻倍 int newCapacity = oldCapacity + ((capacityIncrement > 0) ? capacityIncrement : oldCapacity); // 如果根据扩容方法后容量还是小于minCapacity,那末设置扩容后大小为minCapacity if (newCapacity - minCapacity < 0) newCapacity = minCapacity; //溢出,大于最大允许的容量 if (newCapacity - MAX_ARRAY_SIZE > 0) newCapacity = hugeCapacity(minCapacity); //根据容量重新reallocate内存,得到1个新数组 elementData = Arrays.copyOf(elementData, newCapacity); } // 容量超过最大值处理方式 private static int hugeCapacity(int minCapacity) { if (minCapacity < 0) // overflow throw new OutOfMemoryError(); return (minCapacity > MAX_ARRAY_SIZE) ? Integer.MAX_VALUE : MAX_ARRAY_SIZE; } // 设置vector 的size大小,注意其实不是length,当设置的newsize大于当前的size那末斟酌是不是要扩容,如果小于,那末把过剩的部份全部设置为null public synchronized void setSize(int newSize) { modCount++; if (newSize > elementCount) { ensureCapacityHelper(newSize); } else { for (int i = newSize ; i < elementCount ; i++) { elementData[i] = null; } } elementCount = newSize; } //容量 public synchronized int capacity() { return elementData.length; } //元素个数 public synchronized int size() { return elementCount; } //实际存储的元素是不是为空 public synchronized boolean isEmpty() { return elementCount == 0; } //根据索引生成 对应元素的枚举 ,索引为0 为枚举第1个元素,索引为1为枚举第2个元素,and so on public Enumeration<E> elements() { return new Enumeration<E>() { int count = 0; public boolean hasMoreElements() { return count < elementCount; } //可以看到此方法会抛出异常,在调用的时候务必先调用hasMoreElements进行判断 public E nextElement() { //提供vector对象锁,保持同步 synchronized (Vector.this) { if (count < elementCount) { return elementData(count++); } } throw new NoSuchElementException("Vector Enumeration"); } }; } //辨别是不是存在对象 o public boolean contains(Object o) { return indexOf(o, 0) >= 0; } //返回第1个出现o的位置索引 public int indexOf(Object o) { return indexOf(o, 0); } //主要是判断o是不是为空,其他都是顺序查找,很简单O(n) public synchronized int indexOf(Object o, int index) { if (o == null) { for (int i = index ; i < elementCount ; i++) if (elementData[i]==null) return i; } else { for (int i = index ; i < elementCount ; i++) if (o.equals(elementData[i])) return i; } return -1; } //从数组后端开始查找起,出现的第1个元素 public synchronized int lastIndexOf(Object o) { return lastIndexOf(o, elementCount-1); } //主要是判断o是不是为空,其他都是顺序查找,很简单O(n) public synchronized int lastIndexOf(Object o, int index) { if (index >= elementCount) throw new IndexOutOfBoundsException(index + " >= "+ elementCount); if (o == null) { for (int i = index; i >= 0; i--) if (elementData[i]==null) return i; } else { for (int i = index; i >= 0; i--) if (o.equals(elementData[i])) return i; } return -1; } //方法同等于List接口的get(i)方法说 public synchronized E elementAt(int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } return elementData(index); } public synchronized E firstElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(0); } public synchronized E lastElement() { if (elementCount == 0) { throw new NoSuchElementException(); } return elementData(elementCount - 1); } public synchronized void setElementAt(E obj, int index) { if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } elementData[index] = obj; } public synchronized void removeElementAt(int index) { modCount++; if (index >= elementCount) { throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount); } else if (index < 0) { throw new ArrayIndexOutOfBoundsException(index); } int j = elementCount - index - 1; if (j > 0) { System.arraycopy(elementData, index + 1, elementData, index, j); } elementCount--; elementData[elementCount] = null; /* to let gc do its work */ } public synchronized void insertElementAt(E obj, int index) { modCount++; if (index > elementCount) { throw new ArrayIndexOutOfBoundsException(index + " > " + elementCount); } ensureCapacityHelper(elementCount + 1); System.arraycopy(elementData, index, elementData, index + 1, elementCount - index); elementData[index] = obj; elementCount++; } public synchronized void addElement(E obj) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = obj; } //删除从数组左侧起第1个与obj相等的元素 public synchronized boolean removeElement(Object obj) { modCount++; int i = indexOf(obj); if (i >= 0) { removeElementAt(i); return true; } return false; } //删除所有元素 public synchronized void removeAllElements() { modCount++; // Let gc do its work for (int i = 0; i < elementCount; i++) elementData[i] = null; //gc垃圾回收 elementCount = 0; } // clone克隆Vector,重新生成的数组与原来的数组属于不同援用,重新分配内存 public synchronized Object clone() { try { @SuppressWarnings("unchecked") Vector<E> v = (Vector<E>) super.clone(); v.elementData = Arrays.copyOf(elementData, elementCount); v.modCount = 0; return v; } catch (CloneNotSupportedException e) { // this shouldn't happen, since we are Cloneable throw new InternalError(e); } } public synchronized Object[] toArray() { return Arrays.copyOf(elementData, elementCount); } @SuppressWarnings("unchecked") public synchronized <T> T[] toArray(T[] a) {//泛型指定生成的数组的类型 if (a.length < elementCount) return (T[]) Arrays.copyOf(elementData, elementCount, a.getClass()); System.arraycopy(elementData, 0, a, 0, elementCount); if (a.length > elementCount) a[elementCount] = null; return a; } //没同步,也没判断会不会抛出异常,为何会存在呢?由于这个方法外部不能调用,它由其他内部(public)同步方法调用,保证线程安全 @SuppressWarnings("unchecked") E elementData(int index) { return (E) elementData[index]; } public synchronized E get(int index) { if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); return elementData(index); } //返回的是旧值 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 boolean add(E e) { modCount++; ensureCapacityHelper(elementCount + 1); elementData[elementCount++] = e; return true; } public boolean remove(Object o) { return removeElement(o); } public void add(int index, E element) { insertElementAt(element, index); } //返回被移除的对象 public synchronized E remove(int index) { modCount++; if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index); E oldValue = elementData(index); int numMoved = elementCount - index - 1; if (numMoved > 0) System.arraycopy(elementData, index+1, elementData, index, numMoved); elementData[--elementCount] = null; // Let gc do its work return oldValue; } //清空 public void clear() { removeAllElements(); } // 批量操作,判断vector中是不是包括集合 // 特别注意:判断集合集合中每一个元素是不是都存在vector中,并没有顺序可言,单独判断,复杂度为O(m*n) public synchronized boolean containsAll(Collection<?> c) { return super.containsAll(c); // 父类方法AbstractCollection /* public boolean containsAll(Collection<?> c) { for (Object e : c) if (!contains(e)) return false; return true; } */ } //集合到vector中,会抛出空指针异常 //特别注意:当正在进行此操作的时候,集合C又被另外1个线程修改,那末得到的vector是不肯定的 public synchronized boolean addAll(Collection<? extends E> c) { modCount++; Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); System.arraycopy(a, 0, elementData, elementCount, numNew); elementCount += numNew; return numNew != 0; } // 删除指定集合中切存在于vector中的元素 // 遍历vector中每一个元素,判断是不是存在于collection中,存在则删除,复杂度为O(M*n) public synchronized boolean removeAll(Collection<?> c) { return super.removeAll(c); } // 与前面1个函数功能相反,保存存在于Collection中的vector的元素 public synchronized boolean retainAll(Collection<?> c) { return super.retainAll(c); } //指定索引,插入集合 public synchronized boolean addAll(int index, Collection<? extends E> c) { modCount++; if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index); Object[] a = c.toArray(); int numNew = a.length; ensureCapacityHelper(elementCount + numNew); int numMoved = elementCount - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); elementCount += numNew; return numNew != 0; } // 顺序、值、大小都要相等,使用父类AbstractList方法实现,顺序由listIterator()保证 public synchronized boolean equals(Object o) { return super.equals(o); } public synchronized int hashCode() { return super.hashCode(); } public synchronized String toString() { return super.toString(); } //AbstractCollection方法 /* public String toString() { Iterator<E> it = iterator(); if (! it.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = it.next(); sb.append(e == this ? "(this Collection)" : e); if (! it.hasNext()) return sb.append(']').toString(); sb.append(',').append(' '); } } */ // 根据指定索引,返回子集合 //特别注意: 返回的子集合还是依赖于此vector的,其实不是重新分配内存的 //对子集合的1切操作将会影响vector的变化,比如对子集合的排序(这个利用的非常广)、清空子集合等都会影响vector元素变化,但是与此同时也要斟酌到多线程的不肯定性 //eg:list.subList(from, to).clear();清空 //由于使用了Collections.synchronizedList进行同步处理(对象锁为当前vector对象),因此对vector的操作和对子集合的操作是同步处理的 public synchronized List<E> subList(int fromIndex, int toIndex) { return Collections.synchronizedList(super.subList(fromIndex, toIndex), this); } //删除指定范围子集合 protected synchronized void removeRange(int fromIndex, int toIndex) { modCount++; int numMoved = elementCount - toIndex; System.arraycopy(elementData, toIndex, elementData, fromIndex, numMoved); // Let gc do its work int newElementCount = elementCount - (toIndex-fromIndex); while (elementCount != newElementCount) elementData[--elementCount] = null; } //序列化 private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { final java.io.ObjectOutputStream.PutField fields = s.putFields(); final Object[] data; synchronized (this) { fields.put("capacityIncrement", capacityIncrement); fields.put("elementCount", elementCount); data = elementData.clone(); } fields.put("elementData", data); s.writeFields(); } // 返回指定游标的列表迭代器,此迭代器ListIterator可以向前向后迭代,比普通iterator()方法强大Itr,推荐使用 public synchronized ListIterator<E> listIterator(int index) { if (index < 0 || index > elementCount) throw new IndexOutOfBoundsException("Index: "+index); return new ListItr(index); } //同上1个方法,默许游标位置为起始位置0 public synchronized ListIterator<E> listIterator() { return new ListItr(0); } //返回1个迭代器 public synchronized Iterator<E> iterator() { return new Itr(); } /** * An optimized version of AbstractList.Itr */ //迭代器默许实现,会出现fail-fast机制 private class Itr implements Iterator<E> { int cursor; // index of next element to return int lastRet = -1; // index of last element returned; ⑴ if no such int expectedModCount = modCount; public boolean hasNext() { // Racy but within spec, since modifications are checked // within or after synchronization in next/previous return cursor != elementCount; } public E next() { synchronized (Vector.this) { checkForComodification();//检查在迭代期间,检查vector是不是存在结构修改 int i = cursor; if (i >= elementCount) throw new NoSuchElementException(); cursor = i + 1; return elementData(lastRet = i); } } public void remove() { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.remove(lastRet); expectedModCount = modCount; } cursor = lastRet; lastRet = -1; } @Override public void forEachRemaining(Consumer<? super E> action) { Objects.requireNonNull(action); synchronized (Vector.this) { final int size = elementCount; int i = cursor; if (i >= size) { return; } @SuppressWarnings("unchecked") final E[] elementData = (E[]) Vector.this.elementData; if (i >= elementData.length) { throw new ConcurrentModificationException(); } while (i != size && modCount == expectedModCount) { action.accept(elementData[i++]); } // update once at end of iteration to reduce heap write traffic cursor = i; lastRet = i - 1; checkForComodification(); } } final void checkForComodification() { if (modCount != expectedModCount) throw new ConcurrentModificationException(); } } //列表迭代器,可以向前向后遍历 final class ListItr extends Itr implements ListIterator<E> { ListItr(int index) { super(); cursor = index; } public boolean hasPrevious() { return cursor != 0; } public int nextIndex() { return cursor; } public int previousIndex() { return cursor - 1; } public E previous() { synchronized (Vector.this) { checkForComodification(); int i = cursor - 1; if (i < 0) throw new NoSuchElementException(); cursor = i; return elementData(lastRet = i); } } public void set(E e) { if (lastRet == -1) throw new IllegalStateException(); synchronized (Vector.this) { checkForComodification(); Vector.this.set(lastRet, e); } } public void add(E e) { int i = cursor; synchronized (Vector.this) { checkForComodification(); Vector.this.add(i, e); expectedModCount = modCount; } cursor = i + 1; lastRet = -1; } } //jdk1.8 新加入的方法,遍历vector中每一个元素,并利用于action行动,支持lambda表达式 @Override public synchronized void forEach(Consumer<? super E> action) { Objects.requireNonNull(action); final int expectedModCount = modCount; @SuppressWarnings("unchecked") final E[] elementData = (E[]) this.elementData; final int elementCount = this.elementCount; for (int i=0; modCount == expectedModCount && i < elementCount; i++) { action.accept(elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } //支持lambda表达式,判断是不是复合某种条件,然后做其他操作 @Override @SuppressWarnings("unchecked") public synchronized boolean removeIf(Predicate<? super E> filter) { Objects.requireNonNull(filter); // figure out which elements are to be removed // any exception thrown from the filter predicate at this stage // will leave the collection unmodified int removeCount = 0; final int size = elementCount; final BitSet removeSet = new BitSet(size);//位集合,记录符合条件的元素的索引 final int expectedModCount = modCount; for (int i=0; modCount == expectedModCount && i < size; i++) { @SuppressWarnings("unchecked") final E element = (E) elementData[i]; if (filter.test(element)) { removeSet.set(i); removeCount++; } } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } //删除符合条件的元素,左移 final boolean anyToRemove = removeCount > 0; if (anyToRemove) { final int newSize = size - removeCount; for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) { i = removeSet.nextClearBit(i); elementData[j] = elementData[i]; } for (int k=newSize; k < size; k++) { elementData[k] = null; // Let gc do its work } elementCount = newSize; if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } return anyToRemove; } //支持lambda表达式,对全部元素进行替换操作 @Override @SuppressWarnings("unchecked") public synchronized void replaceAll(UnaryOperator<E> operator) { Objects.requireNonNull(operator); final int expectedModCount = modCount; final int size = elementCount; for (int i=0; modCount == expectedModCount && i < size; i++) { elementData[i] = operator.apply((E) elementData[i]); } if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } // Arrays.sort 排序 @SuppressWarnings("unchecked") @Override public synchronized void sort(Comparator<? super E> c) { final int expectedModCount = modCount; Arrays.sort((E[]) elementData, 0, elementCount, c); if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } modCount++; } /** * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em> * and <em>fail-fast</em> {@link Spliterator} over the elements in this * list. * * <p>The {@code Spliterator} reports {@link Spliterator#SIZED}, * {@link Spliterator#SUBSIZED}, and {@link Spliterator#ORDERED}. * Overriding implementations should document the reporting of additional * characteristic values. * * @return a {@code Spliterator} over the elements in this list * @since 1.8 */ @Override public Spliterator<E> spliterator() { return new VectorSpliterator<>(this, null, 0, -1, 0); } /** Similar to ArrayList Spliterator */ static final class VectorSpliterator<E> implements Spliterator<E> { private final Vector<E> list; private Object[] array; private int index; // current index, modified on advance/split private int fence; // ⑴ until used; then one past last index private int expectedModCount; // initialized when fence set /** Create new spliterator covering the given range */ VectorSpliterator(Vector<E> list, Object[] array, int origin, int fence, int expectedModCount) { this.list = list; this.array = array; this.index = origin; this.fence = fence; this.expectedModCount = expectedModCount; } private int getFence() { // initialize on first use int hi; if ((hi = fence) < 0) { synchronized(list) { array = list.elementData; expectedModCount = list.modCount; hi = fence = list.elementCount; } } return hi; } public Spliterator<E> trySplit() { int hi = getFence(), lo = index, mid = (lo + hi) >>> 1; return (lo >= mid) ? null : new VectorSpliterator<E>(list, array, lo, index = mid, expectedModCount); } @SuppressWarnings("unchecked") public boolean tryAdvance(Consumer<? super E> action) { int i; if (action == null) throw new NullPointerException(); if (getFence() > (i = index)) { index = i + 1; action.accept((E)array[i]); if (list.modCount != expectedModCount) throw new ConcurrentModificationException(); return true; } return false; } @SuppressWarnings("unchecked") public void forEachRemaining(Consumer<? super E> action) { int i, hi; // hoist accesses and checks from loop Vector<E> lst; Object[] a; if (action == null) throw new NullPointerException(); if ((lst = list) != null) { if ((hi = fence) < 0) { synchronized(lst) { expectedModCount = lst.modCount; a = array = lst.elementData; hi = fence = lst.elementCount; } } else a = array; if (a != null && (i = index) >= 0 && (index = hi) <= a.length) { while (i < hi) action.accept((E) a[i++]); if (lst.modCount == expectedModCount) return; } } throw new ConcurrentModificationException(); } public long estimateSize() { return (long) (getFence() - index); } public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED; } } }

Vector使用案例

  • subList() 用法
/** * Created by Genge on 2016-06⑴9. */ public class Solution { public static void main(String[] args) { Vector<String> vector = new Vector<String>(); vector.add("Genge"); vector.add("Hello"); vector.add("World"); System.out.println("处理前的结果:"); Iterator<String> iterator = vector.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } List<String> sublist = vector.subList(1, 2); sublist.clear(); sublist.add("SB"); sublist.add("Huangdou"); System.out.println("处理后结果:"); Iterator<String> iter = vector.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } } }

结果图以下:

生活不易,码农辛苦
如果您觉得本网站对您的学习有所帮助,可以手机扫描二维码进行捐赠
程序员人生
------分隔线----------------------------
分享到:
------分隔线----------------------------
关闭
程序员人生