About Stack
Stack is a stack. Its characteristics are: Advanced post-Exit (FILO, first in the last out). The stack in the Java Toolkit is inherited from vectors (vector queues), since vectors are implemented by arrays, which means that stacks are also implemented through arrays, not linked lists. Of course, we can also use LinkedList as a stack. The inheritance relationship of stack
Java.lang.Object? Java.util.abstractcollection<e> ? Java.util.abstractlist<e> ? Java.util.vector<e> ? Java.util.stack<e>public class Stack<e> extends Vector<e> {}
the relationship between stack and collection is as follows: Stack source parsing (based on jdk1.6.0_45)
PackageJava.util; PublicclassStack<e>extendsVector<e> { //The version ID. This is used for version upgrade control, not to be ignored here! Private Static Final LongSerialversionuid = 1224463164541339165L; //constructor Function PublicStack () {}//push function: Put elements on top of the stack Publice push (E item) {//put the element on top of the stack. //implementation of AddElement () in Vector.javaaddelement (item); returnitem; } //Pop function: Returns the top element of the stack and removes it from the stack Public synchronizede pop () {e obj; intLen =size (); Obj=Peek (); //Remove the top element of the stack, the implementation of Removeelementat () in Vector.javaRemoveelementat (len-1); returnobj; } //Peek function: Returns the top element of the stack without performing a delete operation Public synchronizedE Peek () {intLen =size (); if(len = = 0) Throw Newemptystackexception (); //returns the top element of the stack, ElementAt () specifically implemented in Vector.java returnElementAt (len-1); } //whether the stack is empty Public Booleanempty () {returnSize () = = 0; } //find the position of "element O" in the stack: the number of top of the stack from the bottom of the stack Public synchronized intsearch (Object o) {//Gets the element index, ELEMENTAT () specifically implemented in Vector.java inti =lastIndexOf (o); if(I >= 0) { returnSize ()-i; } return-1; }}View Code
Summary:
- a stack is actually implemented by an array. When the push is executed (that is, the element is pushed into the stack), it is by appending the element to the end of the array. the element at the end of the array is returned when Peek is executed (that is, the top element of the stack is removed and no deletion is performed). When the pop is executed (that is, the top element of the stack is removed, and the element is deleted from the stack), the element at the end of the array is taken out, and then the element is removed from the array.
- Stack inherits from vectors, which means that the properties and functions possessed by the vector are owned by the stack.
Java Stack Source Analysis