溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

如何用源碼分析Vector

發(fā)布時(shí)間:2021-11-09 17:19:02 來(lái)源:億速云 閱讀:117 作者:柒染 欄目:大數(shù)據(jù)

如何用源碼分析Vector,相信很多沒(méi)有經(jīng)驗(yàn)的人對(duì)此束手無(wú)策,為此本文總結(jié)了問(wèn)題出現(xiàn)的原因和解決方法,通過(guò)這篇文章希望你能解決這個(gè)問(wèn)題。

Vector簡(jiǎn)介
public class Vector<E> 
    extends AbstractList<E>
    implements List<E>, RandomAccess, Cloneable, java.io.Serializable{
}
  • Vector繼承了AbstractList,實(shí)現(xiàn)了List;所以它是一個(gè)隊(duì)列,支持添加、刪除、修改、遍歷等操作。

  • Vector實(shí)現(xiàn)了RandomAccess接口,支持快速隨機(jī)訪(fǎng)問(wèn)策略。

  • Vector實(shí)現(xiàn)了Cloneable接口,重寫(xiě)了clone方法,因此可以進(jìn)行克隆。

  • Vector實(shí)現(xiàn)了Serializable接口,因此可以進(jìn)行序列化。

  • Vector的操作是線(xiàn)程安全的

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

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

/** 集合中元素的數(shù)量 **/
protected int elementCount;

/** 集合增長(zhǎng)系數(shù) **/
protected int capacityIncrement;
構(gòu)造函數(shù)
/** 默認(rèn)構(gòu)造函數(shù),初始化容量為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;
}

/** 通過(guò)集合初始化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)

/** 通過(guò)synchronized關(guān)鍵字實(shí)現(xiàn)線(xiàn)程安全 **/
public synchronized boolean add(E e) {
    //確保容量足夠
    ensureCapacityHelper(elementCount + 1);
    //添加元素到集合尾部
    elementData[elementCount++] = e;
    modCount ++;
    return true;
}

private void ensureCapacityHelper(int  minCapacity) {
    //如果大于數(shù)組的容量 通過(guò)grow方法擴(kuò)容
    if (minCapacity > elementData.length) {
        grow(minCapacity);
    }
}

private void grow(int minCapacity) {
    int oldCapacity = elementData.length;
    //如果自增系數(shù)大于0 則每次擴(kuò)容自增數(shù);否則每次擴(kuò)容一倍
    int newCapacity = oldCapacity + capacityIncrement > 0 ? capacityIncrement : oldCapacity;
    //如果擴(kuò)容一次后 仍然小于所需容量 則直接設(shè)置為所需容量
    if (newCapacity < minCapacity) newCapacity = minCapacity;
    //如果擴(kuò)容后大于數(shù)組允許最大容量 如果所需容量大于數(shù)組允許最大容量  則設(shè)置為Integer的最大值,否則設(shè)置為數(shù)組允許的最大容量
    if (newCapacity > MAX_ARRAY_SIZE) newCapacity = minCapacity > MAX_ARRAY_SIZE ? Integer.MAX_VALUE : MAX_ARRAY_SIZE;
    //擴(kuò)容數(shù)組
    elementData = Arrays.copyOf(elementData, newCapacity);
}

add(int index, E element)

/** 通過(guò)insertElementAt方法實(shí)現(xiàn)數(shù)據(jù)的添加及線(xiàn)程安全 **/
public void add(int index, E element) {
    insertElementAt(element, index);
}

addElement(E obj)

/** Vector自有的方法 與add方法除了返回值幾乎沒(méi)有區(qū)別 **/
public synchronized void addElement(E obj) {
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount ++] = obj;
    modCount ++;
}

insertElementAt(E obj, int index)

/** 通過(guò)synchronized關(guān)鍵字實(shí)現(xiàn)線(xiàn)程安全 **/
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;
}
元素移除

移除元素主要有以下幾個(gè)方法:

  • 移除單個(gè)元素的方法;如:remove(int index)remove(Object o)、removeElement(Object obj)、removeElementAt(int index)

  • 移除多個(gè)元素的方法;如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)

//通過(guò)removeElement實(shí)現(xiàn)元素的移除及線(xiàn)程同步
public boolean remove(Object o) {
    return removeElement(o);
}

removeElement(Object obj)

/** 先通過(guò)indexOf方法找到元素  如果找到就通過(guò)removeElementAt方法移除  沒(méi)找到就返回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)方法基本一致 無(wú)返回值 **/
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)

/** 通過(guò)父類(lèi)AbstractCollection的removeAll實(shí)現(xiàn) **/
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;
}

/** 通過(guò)父類(lèi)AbstractCollection的retainAll實(shí)現(xiàn) **/ 
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),兩者方法都通過(guò)上方的elementData(int index)方法實(shí)現(xiàn)

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)兩個(gè)方法,主要是返回值不同。

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

看完上述內(nèi)容,你們掌握如何用源碼分析Vector的方法了嗎?如果還想學(xué)到更多技能或想了解更多相關(guān)內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI