Search
 
SCRIPT & CODE EXAMPLE
 

JAVA

How to create a stack data structure in Java?

public class ArrayBasedStack {
	private Object[] array; // Container for Stack elements
	private int top; // Index of top element
	// Constructor for creating stack of given capacity
	public ArrayBasedStack(int capacity) {
		array = new Object[capacity];
		top = -1;
	}	
	// Method for adding a new element to top of stack
	public void push(Object obj) throws Exception {
		if(size() == array.length) {
			throw new Exception("Stack is full!");
		}
		top++; // Advance to next cell
		array[top] = obj; // Add new element
	}
	// Method for removing element from top of stack
	public Object pop() throws Exception {
		if(isEmpty()) {
			throw new Exception("Stack is empty!");
		}		
		Object toReturn = array[top]; // Element to return
		array[top] = null; // Replace it with null
		top--; // Update top to point to new top
		return toReturn;
	}
	// Method for getting top element without removing it
	public Object top() throws Exception {
		if(isEmpty()) {
			throw new Exception("Stack is empty!");
		}
		return array[top];
	}
	public int size() {
		return top + 1;
	}
	public boolean isEmpty() {
		return (top == -1);
	}
}
Comment

Java Creating a Stack

// Create Integer type stack
Stack<Integer> stacks = new Stack<>();

// Create String type stack
Stack<String> stacks = new Stack<>();
Comment

Java Stack Declaration

public class Stack<E> extends Vector<E>
Comment

PREVIOUS NEXT
Code Example
Java :: copy linked list 
Java :: int x = 3 & 5 
Java :: spring @value default value 
Java :: java asynchronous programming example 
Java :: bfs java 
Java :: declare function in java 
Java :: Fix arabic javafx 
Java :: java try-with-resources 
Java :: intelilj javadoc: error - Malformed locale name: UTF8 
Java :: Implementation of LinkedHashMap Class in Java map 
Java :: java print boolean with spaces 
Java :: an internal error occurred during initializing java tooling . java.lang.nullpointerexception 
Java :: declaring variables views in java android 
Java :: android arraylist to comma separated string 
Java :: java Math.sqrt(double) 
Java :: minecraft fabric client message 
Java :: dockerfile spring boot 
Java :: does not have a NavController set on 2131231008 
Java :: thread in java 
Java :: java foreach letter in word 
Java :: javac encoding utf-8 
Java :: java array object 
Java :: array de meses java 
Java :: how to convert a arraylist to array in java 
Java :: string to words java 
Java :: indexof list java 
Java :: difference between synchronized block and synchronized method example 
Java :: java instanceof operator 
Java :: java packages example 
Java :: java string util if empty default 
ADD CONTENT
Topic
Content
Source link
Name
1+1 =