Data results - Vector, Stack

Vector

Brief introduction

Dynamic array thread-safe, very similar to ArrayList. JDK1.0 add the Vector class. Vector can maintain the same insertion order, but Vector contains many traditional methods, which do not belong to the set frame

class
public class Vector<E>
        extends AbstractList<E>
        implements List<E>, RandomAccess, Cloneable, java.io.Serializable
Attributes
// 元素数组
protected Object[] elementData;
// 元素个数
protected int elementCount;
// 增量长度
protected int capacityIncrement;
// 修改次数, 每次add、remove它的值都会加1(这个属性是AbstractList中的)
protected transient int modCount = 0;
// 默认最大长度
private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
Constructor
public Vector(int initialCapacity, int capacityIncrement) {
    super();
    // 初始长度小于0时抛异常
    if (initialCapacity < 0)
        throw new IllegalArgumentException("Illegal Capacity: "+
                initialCapacity);
    // 创建元素数组
    this.elementData = new Object[initialCapacity];
    // 指定增长长度
    this.capacityIncrement = capacityIncrement;
}
public Vector(int initialCapacity) {
    // 一个参数构造函数默认指定,增长长度为0
    this(initialCapacity, 0);
}
public Vector() {
    // 空参构造函数,制定初始数组长度10
    this(10);
}
public Vector(Collection<? extends E> c) {
    // 参数集合转数组,赋值给元素数组
    elementData = c.toArray();
    // 设置元素个数
    elementCount = elementData.length;
    // 不是Object数组时转为Object数组
    if (elementData.getClass() != Object[].class)
        elementData = Arrays.copyOf(elementData, elementCount, Object[].class);
}

As can be seen from the constructor to create the elements of the array 10 initializes a length, a growth length of only the first constructor with a set value, the other is 0

Based approach
public synchronized int size() {
    // 返回元素个数
    return elementCount;
}
public synchronized boolean isEmpty() {
    // 元素个数为0时返回true
    return elementCount == 0;
}
Set the length
public synchronized void setSize(int newSize) {
    // 修改次数加1
    modCount++;
    // 判断是否需要扩容
    if (newSize > elementCount) {
        ensureCapacityHelper(newSize);
    } else {
        // 参数以后的元素清空掉
        for (int i = newSize ; i < elementCount ; i++) {
            elementData[i] = null;
        }
    }
    elementCount = newSize;
}
private void ensureCapacityHelper(int minCapacity) {
    // 判断新长度是否大于原数组长度,大于则扩容
    if (minCapacity - elementData.length > 0)
        grow(minCapacity);
}

When using the new length of the expansion is less than the length of the new number of elements in the array of the original stage, the new element is greater than the length of the array length

Expansion
private void grow(int minCapacity) {
    // 获取原长度
    int oldCapacity = elementData.length;
    // 获取新长度
    // 增长长度不为0时 新长度=原长度+增长长度
    // 增长长度不为0时 新长度=原长度+增长长度
    int newCapacity = oldCapacity + ((capacityIncrement > 0) ?
            capacityIncrement : oldCapacity);
    // 判断新长度是否够用,不够用使用参数
    if (newCapacity - minCapacity < 0)
        newCapacity = minCapacity;
    // 判断新长度是否越界
    if (newCapacity - MAX_ARRAY_SIZE > 0)
        newCapacity = hugeCapacity(minCapacity);
    elementData = Arrays.copyOf(elementData, newCapacity);
}
private static int hugeCapacity(int minCapacity) {
    // 长度小于0则抛异常
    if (minCapacity < 0)
        throw new OutOfMemoryError();
    // 长度大于默认最大值取Integer最大值
    return (minCapacity > MAX_ARRAY_SIZE) ?
            Integer.MAX_VALUE :
            MAX_ARRAY_SIZE;
}

Vector special expansion, unlike ArrayList, ArrayList no longitudinal expansion growth under normal circumstances is only 1.5 times the original length, and when Vector expansion, first determines whether the length is zero growth, increase the length of use is not 0, 0 when the original length multiplied by 2

Finding Elements

Looking from front to back

public int indexOf(Object o) {
    return indexOf(o, 0);
}
public synchronized int indexOf(Object o, int index) {
    if (o == null) {
        // index为起始位置
        for (int i = index ; i < elementCount ; i++)
            // 查找元素为空
            if (elementData[i]==null)
                return i;
    } else {
        // index为起始位置
        for (int i = index ; i < elementCount ; i++)
            // 查找equals一样的元素
            if (o.equals(elementData[i]))
                return i;
    }
    // 没有找到返回-1
    return -1;
}

From the back to find

public synchronized int lastIndexOf(Object o) {
    return lastIndexOf(o, elementCount-1);
}
public synchronized int lastIndexOf(Object o, int index) {
    // 判断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;
    }
    // 没有找到返回-1
    return -1;
}
Element array operations
public Enumeration<E> elements() {
    // 每次调用此方法都会有一个新对象
    return new Enumeration<E>() {
        int count = 0;

        public boolean hasMoreElements() {
            return count < elementCount;
        }

        public E nextElement() {
            // 虽然方法上没加锁,但是这儿加了,锁的是当前对象
            synchronized (java.util.Vector.this) {
                if (count < elementCount) {
                    return elementData(count++);
                }
            }
            throw new NoSuchElementException("Vector Enumeration");
        }
    };
}

Here passing on Enumeration, Enumeration interface defines the methods, these methods can be enumerated (once to get a) element object in the collection. This traditional interface has been replaced by an iterator, although Enumeration has not been abandoned, but in modern code has been rarely used.
The first element before and after

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 to find elements

E elementData(int index) {
    // 通过索引直接从数组中取值
    return (E) elementData[index];
}
public synchronized E elementAt(int index) {
    // 判断索引是否大于元素个数
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " + elementCount);
    }
    return elementData(index);
}
public synchronized void setElementAt(E obj, int index) {
    // 超过元素个数抛异常
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                elementCount);
    }
    // 根据索引设值
    elementData[index] = obj;
}

Delete the specified elements on location

public synchronized void removeElementAt(int index) {
    modCount++;
    // 判断指定索引是否超过元素个数
    if (index >= elementCount) {
        throw new ArrayIndexOutOfBoundsException(index + " >= " +
                elementCount);
    }
    // 索引不能小于0
    else if (index < 0) {
        throw new ArrayIndexOutOfBoundsException(index);
    }
    // 索引位置以后的元素前向前移动
    int j = elementCount - index - 1;
    if (j > 0) {
        System.arraycopy(elementData, index + 1, elementData, index, j);
    }
    // 元素个数减1
    elementCount--;
    // 最后一个元素置空
    elementData[elementCount] = null; /* to let gc do its work */
}

Insert the element at the specified position

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

Additional elements

public synchronized void addElement(E obj) {
    modCount++;
    // 判断是否需要扩容
    ensureCapacityHelper(elementCount + 1);
    // 末尾增加元素
    elementData[elementCount++] = obj;
}

Removing elements

public synchronized boolean removeElement(Object obj) {
    modCount++;
    // 找到元素位置
    int i = indexOf(obj);
    // 存在就删除
    if (i >= 0) {
        removeElementAt(i);
        return true;
    }
    return false;
}

Delete all of the elements

public synchronized void removeAllElements() {
    modCount++;
    // 遍历索引元素,依次置空
    for (int i = 0; i < elementCount; i++)
        elementData[i] = null;

    elementCount = 0;
}
Add Remove
public synchronized boolean add(E e) {
    modCount++;
    ensureCapacityHelper(elementCount + 1);
    elementData[elementCount++] = e;
    return true;
}
public boolean remove(Object o) {
    return removeElement(o);
}

Add Remove method is to also use the above method, not here in the repeat

Follow the parent class method
public synchronized boolean containsAll(Collection<?> c) {
    return super.containsAll(c);
}
public synchronized boolean removeAll(Collection<?> c) {
    return super.removeAll(c);
}
public synchronized boolean retainAll(Collection<?> c) {
    return super.retainAll(c);
}
public synchronized boolean equals(Object o) {
    return super.equals(o);
}
public synchronized int hashCode() {
    return super.hashCode();
}
public synchronized String toString() {
    return super.toString();
}

The method of the parent class of the interface reference List articles

Inner classes
private class Itr implements Iterator<E>
final class ListItr extends java.util.Vector.Itr implements ListIterator<E>
static final class VectorSpliterator<E> implements Spliterator<E>

Stack

Brief introduction

A stack or deletion can only be inserted in one end of the linear table, last-out table

class
public class Stack<E> extends Vector<E>

Note inherited from Vector

public E push(E item) {
    addElement(item);

    return item;
}
public synchronized E pop() {
    E obj;
    int len = size();
    obj = peek();
    removeElementAt(len - 1);
    return obj;
}
public synchronized E peek() {
    int len = size();
    // 判断长度
    if (len == 0)
        throw new EmptyStackException();
    // 调用Vector中的方法
    return elementAt(len - 1);
}

Own method rarely, mainly on the stack pop

Guess you like

Origin www.cnblogs.com/yuanjiangnan/p/12542540.html