How to create a Generic Stack pop method in java - java

I am currently working on a Stack project where I am creating a generic Stack class. I've been looking on stack overflow for this, but couldn't find it. I need help creating a pop method in my code.
Here is what I have so far:
public class Stack<E>
{
public static final int DEFAULT_CAPACITY = 10;
private E [] elementData;
private int size;
#SuppressWarnings("unchecked")
public Stack()
{
this.elementData = (E[]) new Object[DEFAULT_CAPACITY];
}
#SuppressWarnings("unchecked")
public Stack(int capacity)
{
if(capacity < 0)
{
throw new IllegalArgumentException("capacity " + capacity);
}
this.elementData = (E[]) new Object[capacity];
}
public boolean isEmpty()
{
if(size == 0)
{
return true;
}
else
{
return false;
}
}
/*
The push method should add its parameter to the top of the stack.
*/
public void push(E item)
{
ensureCapacity(size+1);
elementData[size] = item;
size++;
}
private void ensureCapacity(int capacity)
{
if(elementData.length < capacity)
{
int newCapacity = elementData.length * 2 + 1;
elementData = Arrays.copyOf(elementData, newCapacity);
}
}
I need help right here. I need to have the pop method remove and return the element at the top of the stack. If no items
are present, it should throw an "EmptyStackException".
public E pop()
{
if(isEmpty())
{
throw EmptyStackException
}
else
{
}
}
}

I figured it out, I give the credit to #ScaryWombat. The code is:
public E pop()
{
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
return elementData[--size];
}
}

public E pop()
{
E item;
if(isEmpty())
{
throw new EmptyStackException();
}
else
{
item = elementData[size];
size--;
}
return item;
}
You need to make your return variable equal to the top of your stack array and then decrement your stack array. Also, you need to initialize your stack by setting size=0.

Related

Generic stack implementation

I'm trying to implement a generic stack.
Here's the interface
package stack;
public interface Stack<T>{
void push(T number);
T pop();
T peek();
boolean isEmpty();
boolean isFull();
}
Here's the class
package stack;
import java.lang.reflect.Array;
import java.util.EmptyStackException;
public class StackArray <T> implements Stack<T>{
private int maxSize;
private T[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
// #SuppressWarnings("unchecked")
this.array = (T[]) Array.newInstance(StackArray.class, maxSize);
this.top = -1;
}
private T[] resizeArray() {
/**
* create a new array double the size of the old, copy the old elements then return the new array */
int newSize = maxSize * 2;
T[] newArray = (T[]) Array.newInstance(StackArray.class, newSize);
for(int i = 0; i < maxSize; i++) {
newArray[i] = this.array[i];
}
return newArray;
}
public boolean isEmpty() {
return top == -1;
}
public boolean isFull() {
return top == maxSize-1;
}
public void push(T element) {
if(!this.isFull()) {
++top;
array[top] = element;
}
else {
this.array = resizeArray();
array[++top] = element;
}
}
public T pop() {
if(!this.isEmpty())
return array[top--];
else {
throw new EmptyStackException();
}
}
public T peek() {
return array[top];
}
}
Here's the Main class
package stack;
public class Main {
public static void main(String[] args) {
String word = "Hello World!";
Stack <Character>stack = new StackArray<>(word.length());
// for(Character ch : word.toCharArray()) {
// stack.push(ch);
// }
for(int i = 0; i < word.length(); i++) {
stack.push(word.toCharArray()[i]);
}
String reversedWord = "";
while(!stack.isEmpty()) {
char ch = (char) stack.pop();
reversedWord += ch;
}
System.out.println(reversedWord);
}
}
The error is
Exception in thread "main" java.lang.ArrayStoreException: java.lang.Character
at stack.StackArray.push(StackArray.java:40)
at stack.Main.main(Main.java:14)
line 40 is in the push method
array[top] = element;
Side Question:
Any way to suppress the warning in the constructor? :)
The underlying issue is type erasure. The relevant implications of this means that an instance of the Stack class doesn't know it's type arguments at run-time. This is the reason why you can't just use the most natural solution here, array = new T[maxSize].
You've tried to work around this by creating an array using Array.newInstance(...), but unfortunately this array does not have elements of type T either. In the code shown the elements are of type StackArray, which is probably not what you intended.
One common way of dealing with this is to use an array of Object internally to Stack, and cast any return values to type T in accessor methods.
class StackArray<T> implements Stack<T> {
private int maxSize;
private Object[] array;
private int top;
public StackArray(int maxSize) {
this.maxSize = maxSize;
this.array = new Object[maxSize];
this.top = -1;
}
// ... lines removed ...
public T pop() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top--);
}
public T peek() {
if(this.isEmpty())
throw new EmptyStackException();
return element(top);
}
// Safe because push(T) is type checked.
#SuppressWarnings("unchecked")
private T element(int index) {
return (T)array[index];
}
}
Note also you have a bug in the resizeArray() method where maxSize is never assigned a new value. You don't really need to keep track of maxSize, as you could just use array.length.
I think there is also an issue with peek() when the stack is empty in the original code.
Your code creates arrays of StackArray, and then you try to stick Character objects in it, just as if you were doing this:
static void add(Object arr[], Object o) {
arr[0] = o;
}
public static void main(String[] args) {
StackArray stack[] = new StackArray[1];
Character c = 'x';
add(stack, c);
}

Dropout stack is not working

I am trying to create a program where when the stack is full(for example 5 values can be held), and you try to push another value on the stack it performs the DropOut method. Where is sets ex. stack at position 0 to position 1 etc.... all the way to position 3 == to position 4. From here I want to delete the top value on the stack ( in this example it is the value at position 4 (5th value) ) From here I would then be able to add my next value to the top of the stack.... but my code is not working as intended. I am a beginner and appreciate any input available. Thanks for you time.
package jsjf;
import jsjf.exceptions.*;
import java.util.Arrays;
import java.util.*;
public class ArrayStack1<T> implements StackADT<T>
{
private final static int DEFAULT_CAPACITY = 5;
private int top;
private T[] stack;
private int next;
public ArrayStack1()
{
this(DEFAULT_CAPACITY);
}
public ArrayStack1(int initialCapacity)
{
top = -1;
stack = (T[])(new Object[initialCapacity]);
}
public void push(T element)
{
if (top+1==DEFAULT_CAPACITY){
DropOut();
//top=top-1;
pop();
stack[top]=element;
}
top++;
stack[top] = element;
}
public void DropOut(){
for (int x=0; x<stack.length-1; x++){
// if(x==stack.length){
// stack[x]=null;
// }
stack[x]=stack[x+1];
}
}
public T pop() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
T result = stack[top];
stack[top] = null;
return result;
}
public T peek() throws EmptyCollectionException
{
if (isEmpty())
throw new EmptyCollectionException("stack");
return stack[top];
}
public boolean isEmpty()
{
return (top < 0);
}
public int size(){
return (top+1);
}
public String toString()
{
String result = "";
for (int scan=0; scan <= top; scan++)
result = result + stack[scan].toString() + "\n";
return result;
}
public static void main(String[] args) {
ArrayStack1<Integer> t1=new ArrayStack1<Integer>(5);
t1.push(5);
t1.push(3);
t1.push(6);
t1.push(5);
t1.push(3);//
t1.push(4);
}
}
On push you are stacking the element twice when you reach max capacity. An else should fix your issue:
public void push(T element)
{
if (top+1==DEFAULT_CAPACITY){
DropOut();
//top=top-1;
pop();
stack[top]=element;
} else {
top++;
stack[top] = element;
}
}

Generic Array Method Class in Java

I've been trying to turn this generic arraylist class into an array but I haven't been able to get it to work. I've hit a roadblock at the push() and pop() methods. Any help is appreciated.
Here's the original class:
public class GenericStack<E> {
private java.util.ArrayList<E> list = new java.util.ArrayList<E>();
public int getSize() {
return list.size();
}
public E peek() {
return list.get(getSize() - 1);
}
public E push(E o) {
list.add(o);
return o;
}
public E pop() {
E o = list.get(getSize() - 1);
list.remove(getSize() - 1);
return o;
}
public boolean isEmpty() {
return list.isEmpty();
}
}
And here's my revised class so far:
public class GenericStack<E> {
public static int size = 16;
#SuppressWarnings("unchecked")
private E[] list = (E[])new Object[size];
public void add(int index, E e) {
ensureCapacity();
for (int i = size - 1; i >= index; i--) {
list[i + 1] = list[i];
list[index] = e;
size++;
}
}
public int getLength() {
return list.length;
}
public E peek() {
E o = null;
o = list[0];
return o;
}
public E push(E o) {
ensureCapacity();
list.append(o);
size++;
return o;
}
public E pop() {
E o = null;
for (int i = 0; i > list.length; i++) {
o = list[i - 1];
}
list[list.length - 1] = null;
size--;
return o;
}
private void ensureCapacity() {
if (size >= list.length) {
#SuppressWarnings("unchecked")
E[] newlist = (E[])(new Object[size * 2 + 1]);
System.arraycopy(list, 0, newlist, 0, size);
list = newlist;
}
}
public boolean isEmpty() {
if (list.length > 0) {
return false;
}
else {
return true;
}
}
}
NB: You must first correct your code like mentioned in comments.
It's recommended to use name method like of official Stack class, so there are 5 methods: empty() peek() pop() push(E item) search(Object o).
You should declare initial size of your array as a constant and an other variable for current size and all your attributes should be private like that:
private final int MAX_SIZE = 16;
private int currentSize=0;
There is the code of peek() method:
public E peek() {
E o = null;
o = list[currentSize-1];
return o;
}
There is the code of push(E o) method:
public E push(E o) {
list[currentSize]=o;
currentSize++;
return o;
}
There is the code of pop() method this method must throw EmptyStackException - if this stack is empty:
public E pop() {
E o = null;
if(currentSize>0){
o=list[currentSize - 1];
list[currentSize - 1] = null;
currentSize--;
return o;
}else{
throw new EmptyStackException();
}
}
There is the code of empty() method:
public boolean empty() {
if (currentSize > 0) {
return false;
}
else {
return true;
}
}

Solitaire Game using tads(stack, Queue, Deque, List ) in Java - Classe implemented by Stack

I've already started work on drafting Game Solitario with tads and patterns of software in Java and I already started to make the Stack interface
public interface Stack <E> {
// number of elements in the stack
public int size ();
// does not contain elements?
public boolean isEmpty ();
// returns next object to come out without removing
public E peek () throws EmptyStackException;
// add new stack element
public void push (E elem) throws FullStackException;
// pops or drop next element
public E pop () throws EmptyStackException;
}
and here I have a calsss LotOfCard has a collection of cards and have the LIFO behavior and you can check if a lot of cards is empty, put or add new cards in the lot and removing cards from the stack.
public class LotOfCards implements Stack <Card> {
//
private HashSet <Card> cards;//contains collections of Card
//
public LotOfCards() {
this.cards= new HashSet <> ();
}
//
public HashSet <Card> getCards () {
return cards;
}
//
public void setCards (HashSet <Card> cards) {
this.cards= cards;
}
// return number of elements in the stack
Override
public int size() {
return this.cards.size();
}
// does not contain elements?
Override
public boolean isEmpty () {
return (this.cards.isEmpty () || this.cards == null) ;
}
// add new stack element
Override
public void push (Card element) throws FullStackException{
this.cards.add (element);
}
// returns next object to come out without removing
Override
public Card peek () throws EmptyStackException{//Doubt here
if (this.isEmpty ()) {
throw new EmptyStackException ();
}
return (Card) null;
}
// pops or drop element
Override
Public Card pop () throws EmptyStackException{//Doubt here
if (this.isEmpty ()) {
throw new EmptyStackException ();
}
// returns the first letter is removed
Card card = this.peek();
// after the card is removed
this.cards.remove (card); // Doubt
// return card
return card;
}
and I doubt the class LotOfCard in methods peek() and pop(), ie, the method peek () returns the top object () and the method pop () since I've been deleting a chart object within the collection of cards and I have no idea how to do, thanked some explanation about creating the algorithm to develop these methods
#mvw, maybe you have right about An array would by fine to implement a stack data structure
and I made and test this class LotOfCards and it´s fine and this is my answer to this question
public class LotOfCards<Card> implements Stack<Card> {
private Card[] array;
private int top;
private int capacity;//52 cards
//
public LotOfCards(int capacity) {
if (capacity<= 0) {
throw new IllegalArgumentException("The maximum stack size must be greater than 0.\n\n");
} else if (capacity> 52) {
throw new IllegalArgumentException("The maximum stack size should not be greater than 52.\n\n");
}
this.capacity = capacity;
this.array= (Card[]) new Object[capacity];
this.top = -1; // = 0
}
//return size of element in stack
#Override
public int size() {
return (this.top + 1);
}
//stack is empty?
#Override
public boolean isEmpty() {
return (this.top == -1);//==0
}
//stack is full
public boolean isFull() {
return this.capacity == this.size();
}
//add or push the new element in stack
#Override
public void push(Card element) throws FullStackException {
if (isFull()) {
throw new FullStackException();
}
this.array[++top] = element;
}
//return the first element, without pop or drop
#Override
public Card peek() throws EmptyStackException {
if (this.isEmpty()) {
throw new EmptyStackException();
}
return (Card) this.array[this.top];
}
//pop or drop the element on the top
#Override
public Card pop() throws EmptyStackException {
//se for vazio
if (this.isEmpty()) {
throw new EmptyStackException();
}
return (Card) this.array[top--];
}
//for teste
public void invertStack() throws FullStackException {
LotOfCards<Card> stack = new LotOfCards<>(this.capacity);
for (int i = this.top; i >= 0; i--) {
stack.push(this.array[i]);
}
this.array = stack.array;
}
#Override
public String toString() {
StringBuilder str = new StringBuilder();
for (Card element: this.array) {
if (element != null) {
str.append(element);
}
}
return str.toString();
}
}

Incompatible Types Error in Java

I keep receiving an error that says that there are incompatible types. I copied this directly out of a book because we are supposed to make changes to the code to enhance the game of War. I have all of the other classes complete and compiled but this one is giving me fits. Here is the code:
public class ArrayStack<E> implements Stack<E> {
private E[] data;
private int size;
public ArrayStack() {
data = (E[])(new Object[1]);
size = 0;
}
public boolean isEmpty() {
return size == 0;
}
public Object pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public Object peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
protected boolean isFull() {
return size == data.length;
}
public void push(Object target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
protected void stretch() {
E[] newData = (E[])(new Object[data.length * 2]);
for (int i = 0; i < data.length; i++) {
newData[i] = data[i];
}
data = newData;
}
}
The error is occurring in the push() method at the data[size] = target; line.
EDIT:::
I'm now receiving this error.
"type Stack does not take parameters
public class ArrayStack implements Stack"
The stack class is as follows.
public interface Stack<E> {
public boolean isEmpty();
public E peek();
public E pop();
public void push(E target);
}
Change Object to E as the push() method's parameter type.
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
Likewise, you should also change the declare return type of pop() and peek() to E.
public E pop() {
if (isEmpty()) {
throw new EmptyStructureException();
}
size--;
return data[size];
}
public E peek() {
if (isEmpty()) {
throw new EmptyStructureException();
}
return data[size - 1];
}
Now your class is fully generic.
push method is not generic like the rest of the class, change it to:
public void push(E target) {
if (isFull()) {
stretch();
}
data[size] = target;
size++;
}
In any case the JDK ships with the class ArrayDeque which fulfill your requirements without being a piece o code pasted from a book.
ArrayDeque<YourObj> stack = new ArrayDeque<YourObj>();
stack.push(new YourObj());
YourObj head = stack.peek();
head = stack.pop();

Categories

Resources