Objective:
The "LIFO"---is the most basic feature of the stack. Many programming languages have packaged stack tools, this article will lead you to review the stack and attach a simulation stack of the program.
In Java memory allocations, objects are stored in an irregular manner every time an object is instantiated by a new operation. The JVM simply stores the memory addresses of the corresponding objects in the heap in the stack by reference variables after loading a tired and instantiating an object. This can be easily understood by the following sketch:
Based on the memory mechanism of Java itself, plus the stack is a basic data structure. This article will use Java code to implement its own class, its function is similar to the Java internal stack, the implementation of the principle is very similar.
1 PackageStack;2 3 Public classMystack {4 5 Privateobject[] elements;6 Private intsize;7 Private Final Static intcapacity=10;8 9 PublicMystack () {Ten This(capacity); One } A - PublicMystack (intcapacity) { -elements =Newobject[capacity]; the } - - Public voidpush (Object o) { - intlen=elements.length; + if(size>=Len) { -Object[] Temp=Newobject[2*Len]; +System.arraycopy (elements, 0, temp, 0, Len); Aelements=temp; at } -elements[size++]=o; - } - PublicObject Pop () { - returnelements[--size]; - } in PublicObject Peek () { - returnElements[size-1]; to } + Public intGetSize () { - returnsize; the } * Public Booleanempty () { $ returnSize==0;Panax Notoginseng } - the}
Test code:
1 PackageStack;2 3 Public classTeststack {4 5 /**6 * @paramargs7 */8 Public Static voidMain (string[] args) {9 test2 ();Ten } One A Private Static voidtest2 () { -Mystack stack =NewMystack (); - for(inti=1;i<=15;i++){ theStack.push ("str" +i); - } - while(!Stack.empty ()) { - System.out.println (Stack.pop ()); + } -System.out.println ("--end--"); + } A at}
Example Simulation of Java stack