How To Find Size Of Stack Array Java
Sharing is caring
In this post we look at the stack in Java, a data construction that operates on the LIFO principle.
We discuss (clicking the link will take you to the section):
- What is a Stack
- How to implement a Stack using collections and deque
- How to implement a Java stack from scratch
What is a Stack in Java
A stack is a information structure where data is added and removed according to the last-in, first-out principle. You lot push elements on pinnacle of the stack and popular them off the stack. A stack can be implemented using a variety of data structures in Coffee. There is also a dedicated stack course in the Java collections module.
A stack is generally expected to back up the following operations:
- Button a new chemical element on tiptop of the stack
- Pop an element off of the stack
- Retrieve the current size or summit of the stack
- Peek at the outset chemical element in the stack
- Check if the stack is empty
How to Create a Stack in Java
Create a Java Stack using the Collections Module
Using the Java collections module you can create a stack using the dedicated stack form.
import java.util.Stack; ... Stack stack = new Stack();
Push
At present that the stack has been created, you tin push objects on top of it using the push method. The stack nosotros've created doesn't specify a type. At runtime, you lot can push button any type of object you like onto the stack.
stack.push button("String"); stack.push(1); Popular and Peek
If the stack contains objects, you tin can retrieve and remove them using the pop method.
Object chemical element = stack.pop();
If you lot merely want to retrieve the first element without removing it, you tin use the peek method.
Object element = stack.peek();
Specifying Generic Types for the Stack
Every bit you may have noticed, we are retrieving generic Java objects from the stack. Since the stack accepts any blazon of object, we don't know what object we get when nosotros pop them off the stack.
Creating a stack without type constraints is a practice I wouldn't recommend. One time you demand to retrieve objects, you need to peek at the first chemical element, check the blazon, remember, and after cast it at runtime. Otherwise, you go a generic Java object, which isn't very useful in most cases.
if(stack.peek() instanceof Cord ) { String topElement = (String) stack.pop(); } The lawmaking that subsequently makes use of these objects needs to be designed to check or have any type of object.
Instead, yous can constrain the stack to only accept a certain blazon of element.
Stack<String> stack = new Stack<Cord>();
Now you lot tin can just push objects of type string onto the stack, but once you lot pop elements, you tin can exist sure to become a cord.
stack.button("String"); String cord = stack.pop(); Call up the Size of the Stack
Using the size method you lot tin call up the number of elements that are currently on the stack.
Stack<String> stack = new Stack<String>(); stack.push("Cord"); stack.push button("Cord"); int size = stack.size(); System.out.println(size); Hither is the result:
Iterating and Searching the Stack
The stack course besides comes with an inbuilt iterator object. The iterator exposes methods such every bit next() that you tin can utilise to iterate over the elements in the stack.
Stack<String> stack = new Stack<String>(); stack.push("String1"); stack.push("String2"); stack.button("String3"); Iterator it = stack.iterator(); while(information technology.hasNext()){ String s = (String) it.side by side(); System.out.println(south); } Note that the iterator doesn't keep track of the type of object independent in the stack. Therefore we have to cast the element retrieved to a cord. We can do this safely since nosotros have previously type-constrained the stack to only contain strings.
Iteration can be used to notice specific elements. Merely the stack grade also offers an inbuilt method that finds an object and returns its index in the stack.
Stack<String> stack = new Stack<Cord>(); stack.push("String1"); stack.push("String2"); stack.push("String3"); int i = stack.search("String3"); Organisation.out.println(i); Since the chemical element String3 is on meridian of the stack, this returns the index 1.
In other words, we have to pop only one item off the stack to get to the item we want. Since this a stack, where items are piled on top of each other, nosotros can't merely become in and pull out an element. Then if the alphabetize was iii, nosotros would have to pop the 2 items above off the stack to get to the chemical element we want.
Create a Stack using Coffee Deque
Coffee util offers a deque data structure, which can be used in place of a variety of data structures including stacks. The deque offers all the main stack methods including peek, push button, pop and size.
Deque<String> stack = new ArrayDeque<String>(); stack.push("String1"); stack.push("String2"); stack.push button("String3"); System.out.println(stack.size()); System.out.println(stack.peek()); Arrangement.out.println(stack.pop()); Implement a Java Stack from Scratch
We can create our own stack class using Java's assortment to hold the elements. We start past defining a public form named CustomStack with ii private variables. The start variable is an array that holds our information. The second variable is an integer that keeps track of the index of the top of the stack. In the constructor, nosotros require the user to specify the size of the array. The superlative element initially is -1 when the stack is empty. Nosotros set it to minus 1 considering Java starts indexing from 0. And so when the offset chemical element is added, the index of the top equals 0.
public class CustomStack { private int array[]; private int height; CustomStack(int size) { array = new int[size]; top = -1; } } The method to retrieve the size of the stack is the easiest to implement, and it helps us with the implementation of further methods.
public int size(){ render height +1; } Next, nosotros demand a method to check whether the array is full. This is important for the push method considering we need to cheque whether in that location is still infinite available on the stack before adding a new item. Otherwise, nosotros'll see an "index out of bounds" exception.
To make sure that the stack is empty, the size of the stack needs to be smaller than the array contained in it.
public Boolean isFull(){ if(size() < array.length){ return false; } Organisation.out.println("Stack is Full"); return true; } Now nosotros tin can finally implement push button to add new elements to the stack.
public void push button(int element) { if(!isFull() ) { top++; assortment[top] = element; } } Let'south test our implementation and so far. We create a stack of size 2 only attempt to push button three elements onto the stack and think the size. This way, we are testing all methods nosotros accept implemented and so far. We wait that the last push is defenseless past if argument using the isFull method, which in plough uses the size method. In total, the stack should merely have a size of 2.
public static void main(String args[]) { CustomStack stack = new CustomStack(2); stack.push button(4); stack.push(5); stack.push button(6); System.out.println(stack.size()); }
To implement the popular method nosotros first demand a way to cheque that the stack is not empty. We cannot pop annihilation off a stack that has no elements.
public Boolean isEmpty(){ if(size() == 0) render true; return false; } Note the succinct one-line notation in the if argument. If yous only have one statement inside an if statement, y'all don't need foursquare brackets.
With the isEmpty method in place, we tin finally implement the pop method. We check whether the stack is non empty. And then we return the element on top and subsequently decrement the top index by 1. The top– index tells the array to retrieve the top element and then decrement top by one. If nosotros had placed the double minus earlier top –meridian, Java would accept decremented top before using information technology as an index to retrieve an chemical element.
public int popular(){ if(!isEmpty()) { return array[height--]; } return -i; } We check whether our implementation works by pushing one chemical element onto the stack and after attempting to call back 2 elements using pop. The first popular should requite us the element we pushed, while the 2nd popular should return -ane since the stack is empty.
public static void master(String args[]) { CustomStack stack = new CustomStack(two); stack.push(4); Organisation.out.println(stack.popular()); System.out.println(stack.pop()); }
Having implemented popular, peek is fairly simple. It is the aforementioned method as pop without decrementing the top alphabetize.
public int peek(){ if(!isEmpty()) { return array[top]; } return -ane; } That's it. Our custom stack is complete. Hither is the complete code.
public class CustomStack { private int array[]; individual int superlative; CustomStack(int size) { assortment = new int[size]; top = -one; } public int size(){ return tiptop +1; } public void push button(int chemical element) { if(!isFull() ) { top++; array[top] = chemical element; } } public Boolean isFull(){ if(size() < array.length){ return false; } Organization.out.println("Stack is Full"); render true; } public Boolean isEmpty(){ if(size() == 0) return true; return false; } public int pop(){ if(!isEmpty()) { return array[top--]; } return -1; } public int peek(){ if(!isEmpty()) { return array[top]; } return -1; } }
Sharing is caring
How To Find Size Of Stack Array Java,
Source: https://programmathically.com/the-stack-in-java/?utm_source=rss&utm_medium=rss&utm_campaign=the-stack-in-java
Posted by: dozierollare.blogspot.com

0 Response to "How To Find Size Of Stack Array Java"
Post a Comment