Detailed explanation of Java collection stack source code
outline
After learning vector, let's start learning stack. Stack is very simple. It inherits from vector. The learning method is the same as before. First have an overall understanding of stack, and then learn its source code; Finally, learn to use it through examples.
Part 1 Introduction to stack
Stack introduction
Stack is a stack. Its features are: Filo, first in last out.
Stack in the Java toolkit inherits from vector (vector queue). Since vector is implemented through array, it means that stack is also implemented through array rather than linked list. Of course, we can also use LinkedList as a stack! In "detailed introduction (source code analysis) and usage examples of vector in Java Collection Series 06", the data structure of vector has been introduced in detail. The data structure of stack will not be described here.
Inheritance of stack
java. lang.Object ↳ java. util. AbstractCollection
↳ java. util. AbstractList
↳ java. util. Vector
↳ java. util. Stack
public class Stack
extends Vector
{}
The relationship between stack and collection is as follows:
Stack constructor
Stack has only one default constructor, as follows:
Stack() API for stack
Stack is a stack. Its common APIs are as follows:
Since stack and are inherited from vector, it also contains all APIs in vector.
Part 2 stack source code analysis (based on jdk1.6.0_45)
The source code of stack is very simple. Let's learn about it.
Summary:
(01) stack is actually implemented through arrays. When the push is executed (that is, the element is pushed into the stack), the element is appended to the end of the array. When peek is executed (that is, the element at the top of the stack is taken out without deletion), the element at the end of the array is returned. When pop is executed (that is, the element at the top of the stack is taken out and deleted from the stack), the element at the end of the array is taken out and then deleted from the array. (02) stack inherits from vector, which means that stack owns all the attributes and functions owned by vector.
Part 3 vector example
Let's learn how to use stack through an example
Operation results: