import DataStructures.*;
public class StackDemo {
public static void main(String[] args) {
Stack s = new StackArray();
for (int i = 0; i < 8; i++) {
s.push(new Integer(i));
}
while (!s.isEmpty()) {
System.out.println(s.pop());
}
}
}
|
Stack s = new StackArray();The variable s is declared to be of type Stack, which is in fact an interface. Any instance of a class implementing this interface can be assigned to s. Here we have assigned an instance of the StackArray class. But we could have assigned an instance of the StackList class, to be discussed later. If we wanted to be more specific, we could have declared
StackArray s = new StackArray();but there would be nothing gained, since we need no method for s that might be defined publicly in StackArray other than those the class is obliged to implement in virtue of being a Stack. Note that it would certainly be illegal to declare
Stack s = new Stack();since an interface cannot be instantiated directly.
The second point to note is that, when we come to push items onto the stack, we have to write
s.push(new Integer(i));rather than
s.push(i);The reason is that we have defined a generic stack, whose elements are Objects. We must therefore ``objectify'' the primitive types by using the appropriate wrapper classes.
The last comment is to note the use of the isEmpty method, to avoid attempting to pop an element from an empty stack.