P132-P142 栈,数组实现
Implementing Collections
定长栈(fixed-capacity stack)
public class FixedCapacityStackOfStrings
{
private String[] a; // stack entries
private int N; // size
public FixedCapacityStackOfStrings(int cap)
{
a = new String[cap]; } //构造函数,需要指定长度,不支持iteration
public boolean isEmpty() {
return N == 0; }
public int size() {
return N; }
public void push(String item)
{
a[N++] = item; }
public String pop()
{
return a[--N]; }
}
开发一个API的实现最主要的就是选择一种数据结构
使用数组实现非常简单,
- 所有的item都保持在他们插入的位置
- N=0的时候栈为空
- 栈顶 在 a[N-1] 的地方
优点:push 和 pop 与数组的大小无关
缺点
- 泛型:之前的这个只能使用 String,现在我们需要使用泛型来提高它的通用性
public class FixedCapacityStack<Item>
{
private Item[] a; // stack entries
private int N; // size
public FixedCapacityStack(int cap)
{
a = (Item[]) new Object[cap]