07 Stack Implementation
07 Stack Implementation
Implementing a Stack
Reading: Weiss Ch. 3; 3.6; 1.5
1
Related classes
Consider classes for shapes with common features:
• Circle (defined by radius r ):
area = r 2, perimeter =2r r
3
Interface syntax
public interface name {
type name(type name, ..., type name);
type name(type name, ..., type name);
...
}
Example:
// Features common to all shapes.
public interface Shape {
double area();
double perimeter();
}
• Saved as Shape.java
5
Polymorphism
• polymorphism: The client of your classes can use the same code to
work with different types of objects.
public static void printInfo(Shape s) {
System.out.println("The shape: " + s);
System.out.println("area : " + s.area());
System.out.println("perim: " + s.perimeter());
System.out.println();
}
...
Circle circ = new Circle(12.0);
Triangle tri = new Triangle(5, 12, 13);
printInfo(circ);
printInfo(tri);
6
Java ADT interfaces
• Java describes its collection ADTs as interfaces:
public interface Collection<E>
public interface List<E>
public interface Map<K, V>
public class ArrayList<E> implements List<E>
public class LinkedList<E> implements List<E>
public class HashMap<K, V> implements Map<K, V>
• This means you can write one piece of code that can work with any
List, or any Set, or any Collection, ...
public static int max(List<Integer> list) { ...
private Set<String> names;
public Map<String, Integer> getScores() { ...
7
Stacks
• stack: A collection based on the principle of adding elements and
retrieving them in the opposite order.
Last-In, First-Out ("LIFO")
Elements are stored in order of insertion.
• We do not think of them as having indexes.
Client can only add/remove/examine
the last element added (the "top"). push pop, peek
10
Implementing w/ array
public class ArrayIntStack implements IntStack {
private int[] elements;
private int size;
...
}
11
Implementing push
• How do we push an element onto the end of a stack?
public void push(int value) { // just put the element
elements[size] = value; // in the last slot,
size++; // and increase size
}
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 0 0 0 0
size 6
12
Running out of space
• What to do if client needs to add more than 10 elements?
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 4 8 1 6
size 10
Syntax: Arrays.methodName(parameters)
14
Implementing pop
• How do we pop an element off the end of a stack?
public int pop() {
int top = elements[size - 1];
elements[size - 1] = 0; // remove last element
size--; // and decrease size
return top;
}
index 0 1 2 3 4 5 6 7 8 9
value 3 8 9 7 5 12 0 0 0 0
size 6
index 0 1 2 3 4 5 6 7 8 9
value 0 0 0 0 0 0 0 0 0 0
size 0
16
Throwing exceptions
throw new ExceptionType();
throw new ExceptionType("message");
17
Commenting exceptions
• If your method potentially throws any exceptions, you should
comment them in its header; explain what exception and why.
/**
* Removes and returns the top element of the stack.
* Throws an EmptyStackException if stack is empty.
*/
public int pop() {
if (size == 0) {
throw new EmptyStackException();
}
int top = elements[size - 1];
elements[size - 1] = 0; // remove last element
size--; // and decrease size
return top;
}
18
Other methods
• Let's implement the following methods in our stack class:
peek()
Returns the element on top of the stack, without removing it.
size()
Returns the number of elements in the stack.
isEmpty()
Returns true if the stack contains no elements; else false.
(Why write this if we already have the size method?)
clear()
Removes all elements from the stack.
toString()
Returns a string representation of the stack's elements.
19
Type parameters (generics)
List<Type> name = new ArrayList<Type>();
20
Implementing a generic class
// a parameterized (generic) class
public class name<TypeParam> {
...
}
By putting a TypeParam in < >, you are demanding that any client that
constructs your object must supply a type parameter.
• You can require multiple type parameters separated by commas.
• Don't write a specific type like String; write a type variable like T or E.
The client gives a value to that type variable on object construction.
The rest of your class's code can refer to that type by name.
Exercise: Convert our stack interface/class to use generics.
21
Stack<E> ADT interface
• Let's modify our stack interface to be generic.
Anywhere that we expected an int element value, change it to E.
Not all occurrences of int change to E; only ones about elements.
We will also need to modify our ArrayIntStack class...
22
Generic type limitations
public class Foo<T> {
private T myField; // ok
public void method1(T param) {
myField = param; // ok
T temp = new T(); // error
T[] array = new T[10]; // error
}
}