vector原理 java_Java集合 --- Vector底层实现和原理(源码分析)

概述

文章的内容基于JDK1.7进行分析,之所以选用这个版本,是因为1.8的有些类做了改动,增加了阅读的难度,虽然是1.7,但是对于1.8做了重大改动的内容,文章也会进行说明。

Vector作为List的另外一个典型实现类,完全支持List的全部功能,Vector类也封装了一个动态的,允许在分配的Object[]数组,Vector是一个比较古老的集合,JDK1.0就已经存在,建议尽量不要使用这个集合,Vector与ArrayList的主要是区别是,Vector是线程安全的,但是性能比ArrayList要低。

数据结构

继承关系

java.lang.Object

java.util.AbstractCollection

java.util.AbstractList

java.util.Vector

实现接口

Serializable, Cloneable, Iterable, Collection, List, RandomAccess

子类

Stack

基本属性

protected Object[] elementData; //存放元素的数组

protected int elementCount; //已经放入数组的元素个数

protected int capacityIncrement; //数组的增长系数

Vector源码解析

package java.util;

public class Vector

extends AbstractList

implements List, RandomAccess, Cloneable, java.io.Serializable

{

//定义数组,存放元素

protected Object[] elementData;

//已经放入数组的元素数量

protected int elementCount;

//增长的系数

protected int capacityIncrement;

//可序列化版本号

private static final long serialVersionUID = -2767605614048989439L;

//构造方法,提供初始大小,和增长系数

public Vector(int initialCapacity, int capacityIncrement) {

super();

if (initialCapacity < 0)

throw new IllegalArgumentException("Illegal Capacity: "+

initialCapacity);

this.elementData = new Object[initialCapacity];

this.capacityIncrement = capacityIncrement;

}

//构造方法,提供初始大小,增长系数为零

public Vector(int initialCapacity) {

this(initialCapacity, 0);

}

//无参构造方法

public Vector() {

this(10);

}

//构造方法,将指定的集合元素转化为Vector

public Vector(Collection extends E> c) {

elementData = c.toArray();

elementCount = elementData.length;

// c.toArray might (incorrectly) not return Object[] (see 6260652)

//判断c.toArray是否是Object[]类型

if (elementData.getClass() != Object[].class)

elementData = Arrays.copyOf(elementData, elementCount, Object[].class);

}

//将elementData中的元素全部拷贝到anArray数组中

public synchronized void copyInto(Object[] anArray) {

System.arraycopy(elementData, 0, anArray, 0, elementCount);

}

//将数组长度设置为等于vector的个数

public synchronized void trimToSize() {

modCount++;

int oldCapacity = elementData.length;

if (elementCount < oldCapacity) {

elementData = Arrays.copyOf(elementData, elementCount);

}

}

//扩充容量

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;

//根据capacityIncrement进行判断,capacityIncrement> 0 增加capacityIncrement个容量,否则容量扩充当前容量的一倍

int newCapacity = oldCapacity + ((capacityIncrement > 0) ?

capacityIncrement : oldCapacity);

if (newCapacity - minCapacity < 0)

newCapacity = minCapacity;

if (newCapacity - MAX_ARRAY_SIZE > 0)

newCapacity = hugeCapacity(minCapacity);

//扩容操作,生成已给新的数组,容量为newCapacity,并将elementData中的元素全部拷贝到新数组中,并将新生成的数组在赋值给elementData

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;

}

//设置size

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;

}

//返回vector的元素个数

public synchronized int size() {

return elementCount;

}

//是否为空

public synchronized boolean isEmpty() {

return elementCount == 0;

}

//返回vector中全部元素对应的Enumeration

public Enumeration elements() {

//匿名内部类实现

return new Enumeration() {

int count = 0;

public boolean hasMoreElements() {

return count < elementCount;

}

public E nextElement() {

synchronized (Vector.this) {

if (count < elementCount) {

return elementData(count++);

}

}

throw new NoSuchElementException("Vector Enumeration");

}

};

}

//是否包含Object对线o

public boolean contains(Object o) {

return indexOf(o, 0) >= 0;

}

//返回 o 对象的位置

public int indexOf(Object o) {

return indexOf(o, 0);

}

//从index位置开始,向后查找Object对象 (o)

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;

}

//倒序查找对象 o

public synchronized int lastIndexOf(Object o) {

return lastIndexOf(o, elementCount-1);

}

//从最后一个元素开始,向前查找对象o ,找到返回元素的索引,否则返回 -1

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;

}

//返回索引为index的元素

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);

}

//将index位置的元素设置为obj

public synchronized void setElementAt(E obj, int index) {

if (index >= elementCount) {

throw new ArrayIndexOutOfBoundsException(index + " >= " +

elementCount);

}

elementData[index] = obj;

}

//删除指定位置的元素,Object[]对象数组从index+1开始向前依次移动一个位置

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 */

}

//将obj元素插入index位置

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;

}

//删除元素 ,删除成功返回true, 否则返回false

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;

elementCount = 0;

}

//克隆方法

public synchronized Object clone() {

try {

@SuppressWarnings("unchecked")

Vector v = (Vector) 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();

}

}

//转化为数组

public synchronized Object[] toArray() {

return Arrays.copyOf(elementData, elementCount);

}

//转化为指定类型的数组

@SuppressWarnings("unchecked")

public synchronized 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;

}

// Positional Access Operations

@SuppressWarnings("unchecked")

E elementData(int index) {

return (E) elementData[index];

}

//得到索引为index的元素

public synchronized E get(int index) {

if (index >= elementCount)

throw new ArrayIndexOutOfBoundsException(index);

return elementData(index);

}

//设置index位置的元素为element

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);

}

//将element添加到index位置上

public void add(int index, E element) {

insertElementAt(element, index);

}

//删除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();

}

// Bulk Operations

//是否包含集合c中所有的元素

public synchronized boolean containsAll(Collection> c) {

return super.containsAll(c);

}

//将集合c中所有的元素添加到列表中,借助System.copyOf()方法实现

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;

}

//删除集合c中所有的元素

public synchronized boolean removeAll(Collection> c) {

return super.removeAll(c);

}

public synchronized boolean retainAll(Collection> c) {

return super.retainAll(c);

}

//将集合c 添加到index之后的位置上

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;

}

//判断方法

public synchronized boolean equals(Object o) {

return super.equals(o);

}

//计算hashCode值

public synchronized int hashCode() {

return super.hashCode();

}

public synchronized String toString() {

return super.toString();

}

//返回从fromIndex到toIndex之间的子集合

public synchronized List 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();

}

public synchronized ListIterator listIterator(int index) {

if (index < 0 || index > elementCount)

throw new IndexOutOfBoundsException("Index: "+index);

return new ListItr(index);

}

public synchronized ListIterator listIterator() {

return new ListItr(0);

}

public synchronized Iterator iterator() {

return new Itr();

}

//省略了内部类的实现

}

总结

Vector和ArrayList的实现方式可以看出非常的想象,既然Vector类建议尽量少的使用,还是最好不要用了,通过上面的源码发现,每个方法中都添加了synchronized的关键字来保证同步,所以它是线程安全的,但正是这些方法的同步,让它的效率大大的降低了,比ArrayList的效率要慢。

少年听雨歌楼上,红烛昏罗帐。

壮年听雨客舟中,江阔云低,断雁叫西风。

感谢支持!

---起个名忒难

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值