-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayStack.java
More file actions
55 lines (42 loc) · 1.11 KB
/
ArrayStack.java
File metadata and controls
55 lines (42 loc) · 1.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package ch.hslu.AD.SW02.ArrayStack;
import java.util.NoSuchElementException;
import ch.hslu.AD.SW02.ArrayStack.StackFullException;
public class ArrayStack<T> implements Stack<T> {
private int index = 0;
private T[] stack;
@SuppressWarnings("unchecked")
public ArrayStack(int size) {
// See http://stackoverflow.com/a/530289/1336014
this.stack = (T[]) new Object[size]; // c'mon java ... wtf
}
public boolean isEmpty() {
return index == 0;
}
public boolean isFull() {
return index == stack.length;
}
public int size() {
return stack.length;
}
public boolean push(T element) throws StackFullException {
if(isFull()) {
throw new StackFullException(stack.length);
}
stack[index++] = element;
return true;
}
public T pop() {
if(isEmpty()) {
throw new NoSuchElementException("Stack is empty"); // uncool ... there is no point in unchecked exceptions ;)
}
T element = stack[--index];
stack[index] = null; // remove element from stack to allow GC to delete object
return element;
}
public T peek() {
if(isEmpty()) {
return null;
}
return stack[index - 1];
}
}