展开全部
//栈接口
/**
* 2016/10/31 10:19
*
* @author 3306 TODO
*/
public interface StackInterface {
/**
* 压入元素
*
* @param element 元素
*/
void push(T element);
/**
* 弹出栈顶元素
*
* @return T
*/
T pop();
}//固定长度栈62616964757a686964616fe78988e69d8331333361323037
/**
* 2016/10/31 10:03
*
* @param 压入元素类型
* @author 3306 TODO 固定长度栈
*/
public class FixedStack implements StackInterface{
private Object[] objects = new Object[10];
private int index = 0;
/**
* 往固定长度栈压入元素
*
* @param element 元素
* @throws IndexOutOfBoundsException 压缩元素大于栈的容量的时候
*/
public void push(T element) {
if (index > objects.length) {
throw new IndexOutOfBoundsException();
}
objects[index++] = element;
}
/**
* 弹出栈顶元素
*
* @return T
*/
public T pop() {
if (index
throw new IndexOutOfBoundsException();
}
return (T) objects[--index];
}
}//动态栈
import java.util.ArrayList;
import java.util.List;
/**
* 2016/10/31 10:23
*
* @author 3306 TODO
*/
public class FreeStack implements StackInterface {
private List storage = new ArrayList<>();
private int index = 0;
@Override
public void push(T element) {
if (null == element) {
throw new IllegalArgumentException();
}
storage.add(element);
index++;
}
@Override
public T pop() {
if (index
throw new IndexOutOfBoundsException();
}
return storage.get(--index);
}
}//student类
/**
* 2016/10/31 10:11
*
* @author 3306 TODO
*/
public class Student {
private int studentNo;
private String studentName;
public int getStudentNo() {
return studentNo;
}
public void setStudentNo(int studentNo) {
this.studentNo = studentNo;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
@Override
public String toString() {
return "Student{" +
"studentNo=" + studentNo +
", studentName='" + studentName + '\'' +
'}';
}
}//测试类
/**
* 2016/10/31 10:12
*
* @author 3306 TODO
*/
public class TestStack {
public static void main(String[] args) {
testStableStack();
testFreeStack();
}
private static void testStableStack() {
System.out.println("\n\n----------- fixed ------------");
StackInterface myStack = new FixedStack<>();
int numOfStudent = 3;
for (int index = 0; index
Student stu = new Student();
stu.setStudentNo(index);
stu.setStudentName("stu" + index);
myStack.push(stu);
}
for (int index = 0; index
System.out.println(myStack.pop());
}
}
private static void testFreeStack() {
System.out.println("\n\n----------- free ------------");
StackInterface freeStack = new FreeStack<>();
int numOfStudent = 5;
for (int index = 0; index
Student stu = new Student();
stu.setStudentNo(index);
stu.setStudentName("stu" + index);
freeStack.push(stu);
}
for (int index = 0; index
System.out.println(freeStack.pop());
}
}
}