Javaオブジェクトに共通のスタック実装


 

, , 。

1. :

/**
* create on 2010-05-19 TODO:
*
* @author
* @version 1.0
*
*/
class Node {
protected Object data;
protected Node next;

protected Node() {
data = null;
next = null;
}

protected Node(Object _data) {
data = _data;
next = null;
}
}

2. :
/**
* create on 2010-05-19 TODO:
*
* @author
* @version 1.0
*
*/
public class Stack {
private Node top;

public Stack() {
top = null;
}

/**
*
*
* @param obj
*/
public void push(Object obj) {
Node node = new Node(obj);
node.next = top;
top = node;
}

/**
*
*
* @return
* @throws StackException
*/
public Object pop() throws StackException {
if (top == null)
throw new StackException("popping from an empty stack");
else {
Object obj = top.data;
top = top.next;
return obj;
}
}

/**
*
*
* @return
* @throws StackException
*/
public Object peek() throws StackException {
if (top == null)
throw new StackException("peeking into empty stack");
else
return top.data;
}

public boolean isEmpty() {
return (top == null);
}
}

3. :
/**
* create on 2010-05-19 TODO:
*
* @author
* @version 1.0
*
*/
public class StackException extends Exception {
public StackException() {
super("Stack Exception");
}

public StackException(String msg) {
super(msg);
}
}

4. Java :
public class Student {
private String name;
private Integer age;

public Student(String _name, Integer _age) {
name = _name;
age = _age;
}

public String toString() {
return "name=" + name + ", " + "age=" + age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}
}

5. :
/**
* create on 2010-05-19 TODO:
*
* @author
* @version 1.0
*
*/
public class StackApp {

/**
* @param args
* @throws StackException
*/
public static void main(String[] args) throws StackException {
Student s1 = new Student("Alice", 20);
Student s2 = new Student("Bob", 22);
Student s3 = new Student("Jack", 20);
Student s4 = new Student("John", 23);
Student s5 = new Student("Robit", 25);

Stack s = new Stack();
s.push(s1);
s.push(s2);
s.push(s3);
s.push(s4);
s.push(s5);

//s.pop();

while(!s.isEmpty()){
Student st = (Student) s.pop();
System.out.println(st);
}
}

}

6. :
name=Robit, age=25
name=John, age=23
name=Jack, age=20
name=Bob, age=22
name=Alice, age=20