温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

如何用源码分析Vector

发布时间:2021-11-09 17:19:02 来源:亿速云 阅读:106 作者:柒染 栏目:大数据

如何用源码分析Vector,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

Vector简介
public class Vector<E> 
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
}
  • Vector继承了AbstractList,实现了List;所以它是一个队列,支持添加、删除、修改、遍历等操作。

  • Vector实现了RandomAccess接口,支持快速随机访问策略。

  • Vector实现了Cloneable接口,重写了clone方法,因此可以进行克隆。

  • Vector实现了Serializable接口,因此可以进行序列化。

  • Vector的操作是线程安全的

成员变量
/** 集合最大容量 **/
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

/** 保存着添加到Vector中的元素 **/
protected Object[] elementData;

/** 集合中元素的数量 **/
protected int elementCount;

/** 集合增长系数 **/
protected int capacityIncrement;
构造函数
/** 默认构造函数,初始化容量为10 **/
public Vector() {
    this(10);
}

public Vector(int initialCapacity) {
    this(initialCapacity, 0);
}

public Vector(int initialCapacity, int capacityIncrement) {
    if (capacityIncrement < 0) {
        throw new IllegalArgumentException("Illegal Capacity: "+ initialCapacity);
    }
    this.elementData = new Object[initialCapacity];
    this.capacityIncrement = capacityIncrement;
}

/** 通过集合初始化Vector **/
public Vector(Collection<? extends  E> c) {
    elementData = c.toArray();
    elementCount = elementData.length;
    if (elementData.getClass() != Object[].class) {
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
    }
}
元素添加

添加元素主要有add(E e)add(int index, E element)addElement(E obj)insertElementAt(E obj, int index)以及addAll(Collection<? extends E> c) ######add(E e)

/** 通过synchronized关键字实现线程安全 **/
public synchronized boolean add(E e) {
    //确保容量足够
    ensureCapacityHelper(elementCount + 1);
    //添加元素到集合尾部
    elementData[elementCount++] = e;
    modCount ++;
    return true;
}

private void ensureCapacityHelper(int  minCapacity) {
    //如果大于数组的容量 通过grow方法扩容
    if (minCapacity > elementData.length) {
        grow(minCapacity);
    }
}

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //如果自增系数大于0 则每次扩容自增数;否则每次扩容一倍
    int newCapacity = oldCapacity + capacityIncrement > 0 ? capacityIncrement : oldCapacity;
    //如果扩容一次后 仍然小于所需容量 则直接设置为所需容量
    if (newCapacity < minCapacity) newCapacity = minCapacity;
    //如果扩容后大于数组允许最大容量 如果所需容量大于数组允许最大容量  则设置为Integer的最大值,否则设置为数组允许的最大容量
    if (newCapacity > MAX_ARRAY_SIZE) newCapacity = minCapacity > MAX_ARRAY_SIZE ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
    //扩容数组
    elementData = Arrays.copyOf(elementData, newCapacity);
}

add(int index, E element)

/** 通过insertElementAt方法实现数据的添加及线程安全 **/
public void add(int index, E element) {
    insertElementAt(element, index);
}

addElement(E obj)

/** Vector自有的方法 与add方法除了返回值几乎没有区别 **/
public synchronized void addElement(E obj) {
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount ++] = obj;
    modCount ++;
}

insertElementAt(E obj, int index)

/** 通过synchronized关键字实现线程安全 **/
public synchronized void insertElementAt(E obj, int index) {
    //判断index是否越界
    if (index > elementCount) throw new ArrayIndexOutOfBoundsException(index + ">" + elementCount);
    //确保容量足够
    ensureCapacityHelper(elementCount + 1);
    //将index后元素往后移
    System.arraycopy(elementData, index, elementData, index + 1, elementCount - index);
    //添加元素
    elementData[index] = obj;
    elementCount ++;
    modCount ++;
}

addAll(Collection<? extends E> c)

public synchronized boolean addAll(Collection<? extends E> c) {
    Object[] a = c.toArray();
    int numNew = a.length;
    //确保容量足够
    ensureCapacityHelper(elementCount + numNew);
    //添加元素
    System.arraycopy(a, 0, elementData, elementCount, numNew);
    elementCount += numNew;
    modCount ++;
    return numNew != 0;
}

addAll(int index, Collection<? extends E> c)

@Override
public synchronized boolean addAll(int index, Collection<? extends E> c) {
    //判断index是否越界
    if (index < 0 || index > elementCount) throw new ArrayIndexOutOfBoundsException(index + ">" + elementCount);
    Object[] a = c.toArray();
    int numNew = a.length;
    //确保容量足够
    ensureCapacityHelper(elementCount + numNew);
    int needMoved = elementCount - index;
    if (needMoved > 0) {
        //将index后元素往后移
        System.arraycopy(elementData, index, elementData, index + numNew, elementCount - index);
    }
    //添加元素
    System.arraycopy(a, 0, elementData, index, numNew);
    elementCount += numNew;
    modCount ++;
    return numNew != 0;
}
元素移除

移除元素主要有以下几个方法:

  • 移除单个元素的方法;如:remove(int index)remove(Object o)removeElement(Object obj)removeElementAt(int index)

  • 移除多个元素的方法;如removeAll(Collection<?> c)retainAll(Collection<?> c)removeAllElements()

remove(int index)

public synchronized E remove(int index) {
    //判断index是否越界
    if (index < 0 || index >= elementCount) throw new ArrayIndexOutOfBoundsException(index + ">" + elementCount);
    E oldValue = elementData(index);

    int needMoved = elementCount - index - 1;
    if (needMoved > 0) {
        //将index后元素往前移
        System.arraycopy(elementData, index + 1, elementData, index, needMoved);
    }
    elementData[--elementCount] = null;
    modCount ++;
    return  oldValue;
}

/** 查找元素的方法 **/
E elementData(int index) {
    return (E) elementData[index];
}

remove(Object o)

//通过removeElement实现元素的移除及线程同步
public boolean remove(Object o) {
    return removeElement(o);
}

removeElement(Object obj)

/** 先通过indexOf方法找到元素  如果找到就通过removeElementAt方法移除  没找到就返回false **/
public synchronized boolean removeElement(Object obj) {
    modCount ++;
    int i = indexOf(obj);
    if (i > 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

@Override
public int indexOf(Object o) {
    return indexOf(o, 0);
}

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

removeElementAt(int index)

/** 同上方的remove(int index)方法基本一致 无返回值 **/
public synchronized void removeElementAt(int index) {
    if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index + ">" + elementCount);
    else if (index < 0) throw new ArrayIndexOutOfBoundsException(index);
    int needMoved = elementCount - index - 1;
    if (needMoved > 0) {
        //将index后元素往前移
        System.arraycopy(elementData, index + 1, elementData, index, needMoved);
    }
    elementData[--elementCount] = null;
    modCount ++;
}

removeAll(Collection<?> c)

/** 通过父类AbstractCollection的removeAll实现 **/
public synchronized boolean removeAll(Collection<?> c){
    return super.removeAll(c);
}

/** AbstractCollection的removeAll**/
public boolean removeAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<?> it = iterator();
    while (it.hasNext()) {
        if (c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}

/** 通过父类AbstractCollection的retainAll实现 **/ 
public synchronized boolean retainAll(Collection<?> c) {
    return super.retainAll(c);
}

/** AbstractCollection的retainAll**/
public boolean retainAll(Collection<?> c) {
    Objects.requireNonNull(c);
    boolean modified = false;
    Iterator<E> it = iterator();
    while (it.hasNext()) {
        if (!c.contains(it.next())) {
            it.remove();
            modified = true;
        }
    }
    return modified;
}

removeAllElements()

/** 移除所有元素 **/
public synchronized void removeAllElements() {
    for (int i = 0; i < elementCount; i++) {
        elementData[i] = null;
    }
    elementCount = 0;
    modCount ++;
}
元素查找

查找元素主要有get(int index)elementAt(int index),两者方法都通过上方的elementData(int index)方法实现

get(int index)

public E get(int index) {
    if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index);
    return elementData(index);
}
元素更新

更新元素主要有set(int index, E element)setElementAt(E obj, int index)两个方法,主要是返回值不同。

set(int index, E element)

public synchronized E set(int index, E element) {
    if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index);
    E e = elementData(index);
    elementData[index] = element;
    return e;
}

setElementAt(E obj, int index)

public synchronized void setElementAt(E obj, int index) {
    if (index >= elementCount) throw new ArrayIndexOutOfBoundsException(index);
    elementData[index] = obj;
}

看完上述内容,你们掌握如何用源码分析Vector的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI