http://www.iteedu.com/plang/java/javadiary/24.php
https://blog.csdn.net/zhouxukun123/article/details/79314175
1.为什么使用迭代器遍历Vector最慢
2.Verctor重要方法实现
Vector的grow函数
// 传入参数 minCapacity
private void grow(int minCapacity) {
// overflow-conscious code
// 获取老的长度
int oldCapacity = elementData.length;
// 如果构造函数中设置了capacityIncrement并且大于0,那么新的长度
// = 老长度+ capacityIncrement 否则 等于 老长度 + 老长度
int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
capacityIncrement : oldCapacity);
// 如果新的长度仍然小于 minCapacity 那么 新长度 = 传入的minCapcity
if (newCapacity - minCapacity < 0)
newCapacity = minCapacity;
// 长度超过最大长度 设置为HugeCapacity
if (newCapacity - MAX_ARRAY_SIZE > 0)
newCapacity = hugeCapacity(minCapacity);
// 拷贝数组 多余的用 E 的初始值填充,比如 E 为对象就填null;Integer --> null; int --> 0
elementData = Arrays.copyOf(elementData, newCapacity);
}
hugeCapacity(int minCapacity)函数
// Integer.MAX_VALUE = 2^31; DEC: 2147483647
@Native public static final int MAX_VALUE = 0x7fffffff;
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
private static int hugeCapacity(int minCapacity) {
if (minCapacity < 0) // overflow
throw new OutOfMemoryError();
// Ma
return (minCapacity > MAX_ARRAY_SIZE) ?
Integer.MAX_VALUE :
MAX_ARRAY_SIZE;
}
Vector的removeElementAt(int index)函数:移除对应索引的元素
public synchronized void removeElementAt(int index) {
// fail-fase机制,及异常处理
modCount++;
if (index >= elementCount) {
throw new ArrayIndexOutOfBoundsException(index + " >= " +
elementCount);
}
else if (index < 0) {
throw new ArrayIndexOutOfBoundsException(index);
}
// 计算索引index后面的元素个数
int j = elementCount - index - 1;
if (j > 0) {
// 将原数组从index + 1后面开始的全部元素拷贝到原数组index位置上
System.arraycopy(elementData, index + 1, elementData, index, j);
}
// 长度 -1
elementCount--;
// 将数组最后一位置为空,让GC回收垃圾
elementData[elementCount] = null; /* to let gc do its work */
}
Vector迭代:
Vector v = new Vector(10, 10);
v.add("!");
Iterator it = v.iterator();
while (it.hasNext()){
System.out.println(it.next());
}
}
网友评论