I have created 2 classes, one is a generic class ArrayStack<E>
that has all the methods of a stack [i.e. push(), pop(), top(), isEmpty(), size()] and all these methods are implemented on an array (public E arr[];
).This is the constructor which is a part of this class :
public ArrayStack(int capacity) {
arr = (E[]) new Object[capacity];
}
This is the Size() method of above mentioned class :
private int t = -1;
public int size() {
return t + 1;
}
This is the push() method:
public void push(E element) throws IllegalStateException {
if (size() == arr.length) {
throw new IllegalStateException("Stack is full");
}
arr[++t] = element;
}
Another class is class dec_to_bin
which converts decimal to binary which uses the methods of ArrayStack class. Since dec_to_bin class uses methods of previous class I have created object of ArrayStack class in this class
ArrayStack<Long> a1=new ArrayStack<Long>(32);
After converting decimal to binary I am pushing those 1/0s onto the stack but it gives below error
Exception in thread "main" java.lang.IllegalStateException: Stack is full
at ArrayStack.push(test.java:36)
at dec_to_bin.pushing(test.java:64)
at dec_to_bin.process(test.java:75)
at test.main(test.java:115)
pushing(): it is the method that converts dec to binary and pushes onto the stack. You can refer below Pastebin link: https://pastebin.com/CNahygvC