简书 賈小強
转载请注明原创出处,谢谢!
package com.lab1.test1;
import java.util.Iterator;
public class ArrayStack<Item> implements Iterable<Item> {
private int n;
@SuppressWarnings("unchecked")
private Item[] a = (Item[]) new Object[2];
@Override
public Iterator<Item> iterator() {
// TODO Auto-generated method stub
return new ListIterator();
}
private class ListIterator implements Iterator<Item> {
int i = 0;
@Override
public boolean hasNext() {
return i < n;
}
@Override
public Item next() {
Item item = a[i];
i++;
return item;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
for (Item item : this) {
builder.append(item + " ");
}
return builder.toString();
}
private boolean isEmpty() {
return n == 0;
}
private int size() {
return n;
}
private void push(Item item) {
if (n == a.length) {
resize(a.length * 2);
}
a[n++] = item;
}
private Item pop() {
Item item = a[n - 1];
a[n - 1] = null;
n--;
if (n > 0 && n == a.length / 4) {
resize(a.length / 2);
}
return item;
}
@SuppressWarnings("unchecked")
private void resize(int capacity) {
Item[] temp = (Item[]) new Object[capacity];
for (int i = 0; i < n; i++) {
temp[i] = a[i];
}
a = temp;
}
public static void main(String[] args) {
ArrayStack<String> stack = new ArrayStack<>();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.push("bill");
stack.push("jack");
stack.push("lucy");
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
stack.pop();
stack.pop();
System.out.println(stack);
System.out.println(stack.size());
System.out.println(stack.isEmpty());
}
}
输出
0
true
bill jack lucy
3
false
bill
1
false
Happy learning !!