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 Stack Declaration

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

PREVIOUS NEXT
Code Example
Java :: write a name and convert it to an array 
Java :: getting the last value of an integer in java 
Java :: hashmap iteration 
Java :: java separate the numbers from string 
Java :: variable between two numbers java 
Java :: onclick listener android 
Java :: date format android 
Java :: how to use scanners in java 
Java :: java how to check string is number 
Java :: toCharArray() method java 
Java :: static int java 
Java :: string to hexstring In java 
Java :: comparable on a generic class java 
Java :: java terminal colors 
Java :: how to overwrite a text file in java 
Java :: java.lang.IllegalArgumentException: Invalid character found in method name 
Java :: how to generate random id in java 
Java :: java scanner string nextline after nextint 
Java :: caused by: java.lang.noclassdeffounderror: org/springframework/boot/configurationprocessor/json/jsonexception 
Java :: how to read file from console in java 
Java :: print list array 
Java :: spigot disable join message 
Java :: 8.1.1. Declaring an Array&para; 
Java :: find number of occurrences of a substring in a string java 
Java :: javafx change textfield background color 
Java :: how to get child from layout in android 
Java :: java median of list 
Java :: converter float para string em java 
Java :: javafx start 
Java :: mongodb java find all documents 
ADD CONTENT
Topic
Content
Source link
Name
8+4 =