Last active
June 13, 2018 16:19
-
-
Save Apondi/8cd461b93bb52adce415a92fd1dfd935 to your computer and use it in GitHub Desktop.
Implementation of a Java stack
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package stack; | |
/** | |
* | |
* @author kevi | |
* @param <T> | |
*/ | |
public class StackImpl<T> implements Stack<T>{ | |
private T[] data; | |
private int capacity; | |
private int currentItem = 0; | |
StackImpl(int size){ | |
this.capacity = size; | |
this.data = (T[]) new Object[size]; | |
} | |
//the base data structure | |
@Override | |
public boolean empty() { | |
return data.length == 0; | |
} | |
@Override | |
public void pop() { | |
//go to the last object in the array | |
//remove it | |
if(!(empty())){ | |
data[currentItem] = null; | |
currentItem--; | |
} else { | |
System.out.println("Empty stack, you can add items now"); | |
} | |
} | |
@Override | |
public void push(T item) { | |
if(currentItem <= capacity){ | |
data[currentItem] = item; | |
currentItem++; | |
} else { | |
//expand the capacity of the bag | |
expand(); | |
data[currentItem] = item; | |
currentItem++; | |
} | |
} | |
@Override | |
public void peek() { | |
System.out.println(data[currentItem]); | |
} | |
//search for the occurance of the item | |
//if present return the index | |
//if absent return -1 | |
@Override | |
public int search(T item) { | |
for(int i = 0; i< data.length; i++){ | |
if(data[i].equals(item)){ | |
return i; | |
} | |
} | |
return -1; | |
} | |
private void expand() { | |
T[] tempArray = (T[]) new Object[data.length + data.length]; | |
for(int i = 0; i < data.length; i++) | |
tempArray[i] = data[i]; | |
this.data = tempArray; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please add the code for the Stack interface.
A stack is not a static data structure, so you don't need a size parameter for the constructor. Hard-code an initial size of the array.
peek()
should return the item at the top of the stack, so:System.out.println
is not appropriate. e.g. What if the stack is being used in a GUI application?Lines 40-41:
These lines can be made more concise. Recall the definition of the postfix increment and the time of the side-effect.
Aside from the postfix increment modifications described above, could you refactor this code to improve legibility? What if you inverted the condition of the if-statement?
At Line 28:
Does
!empty()
work?pop()
- If I remove an item from the stack, should we remove it from the stack or should we remove it from the stack and return a reference to the removed item? If I take a plate from a stack of plates, its likely I want to use it to wash or place my food on it.