一、 实践了泛型编程
二、利用了java提供的迭代器
三、内部类
四、数据抽象
五、可变数组的实现技巧(1/2和1/4)
六、在main中放入API最小测试实例
import java.lang.Iterable; import java.util.Iterator; public class Stack<Item> implements Iterable<Item> { private Item[] a; private int top; public Stack(){ } public boolean isEmpty(){ return top < 0; } public int size(){ return a.length; } public Stack(int size){ a = (Item[]) new Object[size]; top = -1; } public void push(Item ele){ resize(); a[++top]= ele; } public Item pop(){ resize(); return a[top--]; } private void resize(){ if(a.length==0) a = (Item[]) new Object[1]; else if ((top+1) >= a.length/2){ Item[] temp = (Item[]) new Object[a.length*2]; for(int i =0; i< top+1; i++) temp[i]= a[i]; a = temp; }else if((top+1) <= a.length/4){ Item[] temp = (Item[]) new Object[a.length/2]; for(int i =0; i< top+1; i++) temp[i]= a[i]; a = temp; } } public Iterator<Item> iterator(){ class dataarray implements Iterator<Item> { private int t =top; public boolean hasNext(){ return t>=0; } public Item next(){ return a[t--]; } public void remove(){ } } return new dataarray(); } public static void main(String[] args) { // TODO Auto-generated method stub //String Stack<String> stk = new Stack<String>(2); stk.push("first"); stk.push("second"); stk.pop(); stk.push("third"); stk.push("fourth"); stk.push("fifth"); for(String str:stk){ System.out.println(str); } //Double Stack<Double> stk_val = new Stack<Double>(0); stk_val.push(1.0); stk_val.push(2.0); stk_val.pop(); stk_val.push(3.0); stk_val.push(4.0); stk_val.push(5.0); for(double val:stk_val){ System.out.println(val); } } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-05 18:09:01