首页 / JAVA / Java源代码分析之Vector数组
Java源代码分析之Vector数组
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Java源代码分析之Vector数组,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含22068字,纯文字阅读大概需要32分钟。
内容图文
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 一般都比 size 大。
当知道需要插入大量元素时,可以提前分配给vector较大空间,减少分配内存次数, 从而减少不必要的开销。
此类的iterator和listIterator方法返回的迭代器是快速失败的:如果该向量在任何时间从结构上修改创建迭代器后,
以任何方式,除了通过迭代器自身的remove或add方法,迭代器都将抛出ConcurrentModificationException。
因此,在并发的修改,迭代器很快就会完全失败,而不是在将来不确定的时间任意冒险,不确定性的行为。
通过elements方法返回的Enumeration不是快速失败的。
注意,迭代器的快速失败行为不能得到保证,因为它是,一般来说,
不可能作出任何硬性保证不同步并发修改的存在。快速失败迭代器抛出ConcurrentModificationException尽最大努力的基础上。
因此,这将是错误的编写一个程序,依赖于此异常为它的正确性:
迭代器的快速失败行为应该仅用于检测bug。
从Java 2平台v1.2,这个类是改进来实现List接口,使它成为Java Collections Framework的成员。
不同的是新的集合实现不同,Vector是同步的。
如果不需要线程安全执行,建议代替矢量的使用的ArrayList。
*/publicclassVector<E>
extendsAbstractList<E>
implementsList<E>, RandomAccess, Cloneable, java.io.Serializable
{// 存放数据的数组protected Object[] elementData;
// 实际元素个数protectedint elementCount;
// 容量增量,每次扩容增加的大小,如果 capacityIncrement小雨或等于0,那么容量会每次翻倍double的增长protectedint capacityIncrement;
privatestaticfinallong serialVersionUID = -2767605614048989439L;
// 数组的初始化,增量的初始化,容量小于0会报异常publicVector(int initialCapacity, int capacityIncrement) {
super();
if (initialCapacity < 0)
thrownew IllegalArgumentException("Illegal Capacity: "+
initialCapacity);
this.elementData = new Object[initialCapacity];
this.capacityIncrement = capacityIncrement;
}
// 指定容量,并且增量为0,每次扩容方法为翻倍publicVector(int initialCapacity) {
this(initialCapacity, 0);
}
//默认构造方法,默认容量大小为10publicVector() {
this(10);
}
// 根据指定集合创建vector// 另外vector的顺序由集合Collection的iterator遍历的顺序来保证publicVector(Collection<? extends E> c) {
elementData = c.toArray(); // 根据集合生成数组,数组是reallocate的,不存在refer关系
elementCount = elementData.length;
//下面一句话简单理解就是 toArray()返回的并不一定是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
*/publicsynchronizedvoidcopyInto(Object[] anArray) {
System.arraycopy(elementData, 0, anArray, 0, elementCount);
}
// 去掉Vector 数组后面未存入数据的部分,使得Capacity(length) = elementCountpublicsynchronizedvoidtrimToSize() {
//这个 字段含义为 vector 结构(一般指的是大小)被修改的次数
modCount++;
int oldCapacity = elementData.length;
if (elementCount < oldCapacity) {
elementData = Arrays.copyOf(elementData, elementCount);
}
}
//扩容函数(对外暴露的函数,实现看grow)publicsynchronizedvoidensureCapacity(int minCapacity) {
if (minCapacity > 0) {
modCount++;
ensureCapacityHelper(minCapacity);
}
}
privatevoidensureCapacityHelper(int minCapacity) {
// overflow-conscious codeif (minCapacity - elementData.length > 0)
grow(minCapacity);
}
privatestaticfinalint MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
//这个才是看的重点,上面两个函数可以忽略掉。。。额,说错了,不是忽略掉而是可以不看privatevoidgrow(int minCapacity) {
// overflow-conscious codeint oldCapacity = elementData.length;
// 如果增量大于0那么是的容量+Increment,如果小于等于0,那么容量翻倍int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
// 如果根据扩容方法后容量还是小于minCapacity,那么设置扩容后大小为minCapacityif (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
//溢出,大于最大允许的容量if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
//根据容量重新reallocate内存,得到一个新数组
elementData = Arrays.copyOf(elementData, newCapacity);
}
// 容量超过最大值处理方式privatestaticinthugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflowthrownew OutOfMemoryError();
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
// 设置vector 的size大小,注意并不是length,当设置的newsize大于当前的size那么考虑是否要扩容,如果小于,那么把多余的部分全部设置为nullpublicsynchronizedvoidsetSize(int newSize) {
modCount++;
if (newSize > elementCount) {
ensureCapacityHelper(newSize);
} else {
for (int i = newSize ; i < elementCount ; i++) {
elementData[i] = null;
}
}
elementCount = newSize;
}
//容量publicsynchronizedintcapacity() {
return elementData.length;
}
//元素个数publicsynchronizedintsize() {
return elementCount;
}
//实际存储的元素是否为空publicsynchronizedbooleanisEmpty() {
return elementCount == 0;
}
//根据索引生成 对应元素的枚举 ,索引为0 为枚举第一个元素,索引为1为枚举第二个元素,and so onpublic Enumeration<E> elements() {
returnnew Enumeration<E>() {
int count = 0;
publicbooleanhasMoreElements() {
return count < elementCount;
}
//可以看到此方法会抛出异常,在调用的时候务必先调用hasMoreElements进行判断public E nextElement() {
//提供vector对象锁,保持同步synchronized (Vector.this) {
if (count < elementCount) {
return elementData(count++);
}
}
thrownew NoSuchElementException("Vector Enumeration");
}
};
}
//判别是否存在对象 opublicbooleancontains(Object o) {
return indexOf(o, 0) >= 0;
}
//返回第一个出现o的位置索引publicintindexOf(Object o) {
return indexOf(o, 0);
}
//主要是判断o是否为空,其他都是顺序查找,很简单O(n)publicsynchronizedintindexOf(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;
}
//从数组后端开始查找起,出现的第一个元素publicsynchronizedintlastIndexOf(Object o) {
return lastIndexOf(o, elementCount-1);
}
//主要是判断o是否为空,其他都是顺序查找,很简单O(n)publicsynchronizedintlastIndexOf(Object o, int index) {
if (index >= elementCount)
thrownew 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)方法说publicsynchronized E elementAt(int index) {
if (index >= elementCount) {
thrownew ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
}
return elementData(index);
}
publicsynchronized E firstElement() {
if (elementCount == 0) {
thrownew NoSuchElementException();
}
return elementData(0);
}
publicsynchronized E lastElement() {
if (elementCount == 0) {
thrownew NoSuchElementException();
}
return elementData(elementCount - 1);
}
publicsynchronizedvoidsetElementAt(E obj, int index) {
if (index >= elementCount) {
thrownew ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elementData[index] = obj;
}
publicsynchronizedvoidremoveElementAt(int index) {
modCount++;
if (index >= elementCount) {
thrownew ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
elseif (index < 0) {
thrownew 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 */
}
publicsynchronizedvoidinsertElementAt(E obj, int index) {
modCount++;
if (index > elementCount) {
thrownew ArrayIndexOutOfBoundsException(index
+ " > " + elementCount);
}
ensureCapacityHelper(elementCount + 1);
System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
elementData[index] = obj;
elementCount++;
}
publicsynchronizedvoidaddElement(E obj) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = obj;
}
//删除从数组左边起第一个与obj相等的元素publicsynchronizedbooleanremoveElement(Object obj) {
modCount++;
int i = indexOf(obj);
if (i >= 0) {
removeElementAt(i);
returntrue;
}
returnfalse;
}
//删除所有元素publicsynchronizedvoidremoveAllElements() {
modCount++;
// Let gc do its workfor (int i = 0; i < elementCount; i++)
elementData[i] = null; //gc垃圾回收
elementCount = 0;
}
// clone克隆Vector,重新生成的数组与原来的数组属于不同引用,重新分配内存publicsynchronized 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 Cloneablethrownew InternalError(e);
}
}
publicsynchronized Object[] toArray() {
return Arrays.copyOf(elementData, elementCount);
}
@SuppressWarnings("unchecked")
publicsynchronized <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];
}
publicsynchronized E get(int index) {
if (index >= elementCount)
thrownew ArrayIndexOutOfBoundsException(index);
return elementData(index);
}
//返回的是旧值publicsynchronized E set(int index, E element) {
if (index >= elementCount)
thrownew ArrayIndexOutOfBoundsException(index);
E oldValue = elementData(index);
elementData[index] = element;
return oldValue;
}
publicsynchronizedbooleanadd(E e) {
modCount++;
ensureCapacityHelper(elementCount + 1);
elementData[elementCount++] = e;
returntrue;
}
publicbooleanremove(Object o) {
return removeElement(o);
}
publicvoidadd(int index, E element) {
insertElementAt(element, index);
}
//返回被移除的对象publicsynchronized E remove(int index) {
modCount++;
if (index >= elementCount)
thrownew 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 workreturn oldValue;
}
//清空publicvoidclear() {
removeAllElements();
}
// 批量操作,判断vector中是否包含集合// 特别注意:判断集合集合中每个元素是否都存在vector中,并没有顺序可言,单独判断,复杂度为O(m*n)publicsynchronizedbooleancontainsAll(Collection<?> c) {
returnsuper.containsAll(c);
// 父类方法AbstractCollection/*
public boolean containsAll(Collection<?> c) {
for (Object e : c)
if (!contains(e))
return false;
return true;
}
*/
}
//集合到vector中,会抛出空指针异常//特别注意:当正在进行此操作的时候,集合C又被另外一个线程修改,那么得到的vector是不确定的publicsynchronizedbooleanaddAll(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)publicsynchronizedbooleanremoveAll(Collection<?> c) {
returnsuper.removeAll(c);
}
// 与前面一个函数功能相反,保留存在于Collection中的vector的元素publicsynchronizedbooleanretainAll(Collection<?> c) {
returnsuper.retainAll(c);
}
//指定索引,插入集合publicsynchronizedbooleanaddAll(int index, Collection<? extends E> c) {
modCount++;
if (index < 0 || index > elementCount)
thrownew 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()保证publicsynchronizedbooleanequals(Object o) {
returnsuper.equals(o);
}
publicsynchronizedinthashCode() {
returnsuper.hashCode();
}
publicsynchronized String toString() {
returnsuper.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的,并不是重新分配内存的//对子集合的一切操作将会影响vector的变化,比如对子集合的排序(这个应用的非常广)、清空子集合等都会影响vector元素变化,但是与此同时也要考虑到多线程的不确定性//eg:list.subList(from, to).clear();清空//由于使用了Collections.synchronizedList进行同步处理(对象锁为当前vector对象),因此对vector的操作和对子集合的操作是同步处理的publicsynchronized List<E> subList(int fromIndex, int toIndex) {
return Collections.synchronizedList(super.subList(fromIndex, toIndex),
this);
}
//删除指定范围子集合protectedsynchronizedvoidremoveRange(int fromIndex, int toIndex) {
modCount++;
int numMoved = elementCount - toIndex;
System.arraycopy(elementData, toIndex, elementData, fromIndex,
numMoved);
// Let gc do its workint newElementCount = elementCount - (toIndex-fromIndex);
while (elementCount != newElementCount)
elementData[--elementCount] = null;
}
//序列化privatevoidwriteObject(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,推荐使用publicsynchronized ListIterator<E> listIterator(int index) {
if (index < 0 || index > elementCount)
thrownew IndexOutOfBoundsException("Index: "+index);
returnnew ListItr(index);
}
//同上一个方法,默认游标位置为起始位置0publicsynchronized ListIterator<E> listIterator() {
returnnew ListItr(0);
}
//返回一个迭代器publicsynchronized Iterator<E> iterator() {
returnnew Itr();
}
/**
* An optimized version of AbstractList.Itr
*///迭代器默认实现,会出现fail-fast机制privateclassItrimplementsIterator<E> {int cursor; // index of next element to returnint lastRet = -1; // index of last element returned; -1 if no suchint expectedModCount = modCount;
publicbooleanhasNext() {
// Racy but within spec, since modifications are checked// within or after synchronization in next/previousreturn cursor != elementCount;
}
public E next() {
synchronized (Vector.this) {
checkForComodification();//检查在迭代期间,检查vector是否存在结构修改int i = cursor;
if (i >= elementCount)
thrownew NoSuchElementException();
cursor = i + 1;
return elementData(lastRet = i);
}
}
publicvoidremove() {
if (lastRet == -1)
thrownew IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.remove(lastRet);
expectedModCount = modCount;
}
cursor = lastRet;
lastRet = -1;
}
@OverridepublicvoidforEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
synchronized (Vector.this) {
finalint size = elementCount;
int i = cursor;
if (i >= size) {
return;
}
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) Vector.this.elementData;
if (i >= elementData.length) {
thrownew 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();
}
}
finalvoid checkForComodification() {
if (modCount != expectedModCount)
thrownew ConcurrentModificationException();
}
}
//列表迭代器,可以向前向后遍历final class ListItr extends Itr implements ListIterator<E> {
ListItr(int index) {
super();
cursor = index;
}
publicbooleanhasPrevious() {
return cursor != 0;
}
publicintnextIndex() {
return cursor;
}
publicintpreviousIndex() {
return cursor - 1;
}
public E previous() {
synchronized (Vector.this) {
checkForComodification();
int i = cursor - 1;
if (i < 0)
thrownew NoSuchElementException();
cursor = i;
return elementData(lastRet = i);
}
}
publicvoidset(E e) {
if (lastRet == -1)
thrownew IllegalStateException();
synchronized (Vector.this) {
checkForComodification();
Vector.this.set(lastRet, e);
}
}
publicvoidadd(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表达式@OverridepublicsynchronizedvoidforEach(Consumer<? super E> action) {
Objects.requireNonNull(action);
finalint expectedModCount = modCount;
@SuppressWarnings("unchecked")
final E[] elementData = (E[]) this.elementData;
finalint elementCount = this.elementCount;
for (int i=0; modCount == expectedModCount && i < elementCount; i++) {
action.accept(elementData[i]);
}
if (modCount != expectedModCount) {
thrownew ConcurrentModificationException();
}
}
//支持lambda表达式,判断是否复合某种条件,然后做其他操作@Override@SuppressWarnings("unchecked")
publicsynchronizedbooleanremoveIf(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 unmodifiedint removeCount = 0;
finalint size = elementCount;
final BitSet removeSet = new BitSet(size);//位集合,记录符合条件的元素的索引finalint 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) {
thrownew ConcurrentModificationException();
}
//删除符合条件的元素,左移finalboolean anyToRemove = removeCount > 0;
if (anyToRemove) {
finalint 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) {
thrownew ConcurrentModificationException();
}
modCount++;
}
return anyToRemove;
}
//支持lambda表达式,对全部元素进行替换操作@Override@SuppressWarnings("unchecked")
publicsynchronizedvoidreplaceAll(UnaryOperator<E> operator) {
Objects.requireNonNull(operator);
finalint expectedModCount = modCount;
finalint size = elementCount;
for (int i=0; modCount == expectedModCount && i < size; i++) {
elementData[i] = operator.apply((E) elementData[i]);
}
if (modCount != expectedModCount) {
thrownew ConcurrentModificationException();
}
modCount++;
}
// Arrays.sort 排序@SuppressWarnings("unchecked")
@Overridepublicsynchronizedvoidsort(Comparator<? super E> c) {
finalint expectedModCount = modCount;
Arrays.sort((E[]) elementData, 0, elementCount, c);
if (modCount != expectedModCount) {
thrownew 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
*/@Overridepublic Spliterator<E> spliterator() {
returnnew VectorSpliterator<>(this, null, 0, -1, 0);
}
/** Similar to ArrayList Spliterator */staticfinal class VectorSpliterator<E> implements Spliterator<E> {
privatefinal Vector<E> list;
private Object[] array;
privateint index; // current index, modified on advance/splitprivateint fence; // -1 until used; then one past last indexprivateint 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;
}
privateintgetFence() { // initialize on first useint 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")
publicbooleantryAdvance(Consumer<? super E> action) {
int i;
if (action == null)
thrownew NullPointerException();
if (getFence() > (i = index)) {
index = i + 1;
action.accept((E)array[i]);
if (list.modCount != expectedModCount)
thrownew ConcurrentModificationException();
returntrue;
}
returnfalse;
}
@SuppressWarnings("unchecked")
publicvoidforEachRemaining(Consumer<? super E> action) {
int i, hi; // hoist accesses and checks from loop
Vector<E> lst; Object[] a;
if (action == null)
thrownew 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;
}
}
thrownew ConcurrentModificationException();
}
publiclongestimateSize() {
return (long) (getFence() - index);
}
publicintcharacteristics() {
return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
}
}
}
Vector使用案例
-
subList()
用法
/**
* Created by Genge on 2016-06-19.
*/
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());
}
}
}
结果图如下:
原文:http://blog.csdn.net/huzhigenlaohu/article/details/51769082
内容总结
以上是互联网集市为您收集整理的Java源代码分析之Vector数组全部内容,希望文章能够帮你解决Java源代码分析之Vector数组所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。