Custom Stack Implementation in java


In the collection framework, stack comes with the extended functionalities of Vector class. There are 5 functionalities in the stack class which are the extension of vector class functionalities.


There are 2 different ways to implement stack - 
  1. Using Array
  2. Using ArrayList


1. Using Array: Array is the basic memory for any implementation in java. We will see how to implement it using array. To build custom stack, please follow below steps:
Declare StackArray class and it's constructor:


Below image depicts that the above piece of code registers the two indexes space in memory and points to idx at 0 position:


Now add the method of push and pop to the class which will take care of addition and removal of element to the stack:


Our basic functionality of stack is ready. Now we will add the support functions to it:


These size and print methods will help us while running the program to get the current status of the stack.

Now have few methods to optimize the memory too so that when we have the more elements we should have more memory available to save the elements and when we shrink our elements in stack our stack must occupy less memory.


Let's make the corresponding changes in the push and pop methods:


Now the full stackarray class would look like :


To test the code we can have our class:


Output:
===========
klm
xyz
def
abc
===========
Pop--klm
Pop--xyz
===========
def
abc
===========
Pop--def
Pop--abc
Stack is empty
Pop--null
Stack is empty
Pop--null
===========
347
897
8
===========
===========
8
===========
2

Number example in images
Now stack is full. When new element would come, it would first call the expand method and double its size and then push the element into the stack:

Now when pop element is called, it pops the element and check the size too. If the half of size is greater than initial size and collapse of stack happens:

This is how the stack push and pop methods work and it manages the memory.


Look at my other posts:

Some other interesting blogs:

Comments

Popular posts from this blog

List - Insertion order

Custom LinkedList Implementation