Chapter 9 Java Collection of Vector and Stack Source Code Analysis

Preface

Look at the next picture first
Insert picture description here

Vector

Vector and ArrayList are both inherited from the same parent class AbstractList, and they have the same internal method implementation. Therefore they belong to brotherhood. But ArrayList is a thread-unsafe collection, Vector is a thread-safe collection, the reason is that all APIs have added the synchronization keyword synchronized. In other respects, they look exactly the same, whether it is an internally maintained array or the method implemented by its Api. Therefore, to understand Vector in detail, you only need to understand ArrayList in detail. The source code analysis address of ArrayList is attached below:
Chapter 6 ArrayList source code analysis of JAVA collection

Stack

As you can see from the above figure, Stack inherits Vector, so it also maintains an array inside. Some APIs are also modified by synchronized, so it is also a thread-safe collection. The specific details are analyzed below.
Stack is a subclass of Vector. In addition to inheriting the functions of its father, it also provides some stack operations, such as push, pop, and peek. The approximate functions are as follows:

public E push(E item)        // 将元素放在栈顶,栈顶,也是就数组elementData的末尾。
public synchronized E pop()  // 删除栈顶元素
public synchronized E peek() // 获取栈顶元素
public boolean empty()   
public synchronized int search(Object o)  // 从栈顶向下寻找元素,也就是从elementData的尾部向头部寻找。

push(E item)

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

    return item;
}

This method is not modified with synchronized, which means that you can add elements to the top of the stack at the same time? In fact, it is not. It calls the addElement() method internally, which is modified by synchronized.

pop()

public synchronized E pop() {
    E       obj;
    int     len = size();

    obj = peek();
    removeElementAt(len - 1);

    return obj;
}

peek()

 public synchronized E peek() {
    int     len = size();

    if (len == 0)
        throw new EmptyStackException();
    return elementAt(len - 1);
}

search(Object o)

public synchronized int search(Object o) {
    int i = lastIndexOf(o);

    if (i >= 0) {
        return size() - i;
    }
    return -1;
}

The above codes are relatively simple and will not be analyzed.
It should be noted that the bottom layer uses an array to implement a collection, and when adding elements internally, expansion needs to be considered, whether it is ArrayList, Vector or Stack.

Guess you like

Origin blog.csdn.net/weixin_43901067/article/details/105052611
Recommended