用Java制作堆栈方法



有什么简单的方法可以让堆栈显示,然后在方法"PrintAndEmpty"中清空它自己吗?我需要方法PrintAndEmpty中的print和empty,而不是main。代码为:

 import java.util.*;
 class Stack<E> implements StackInterface<E> {
 private ArrayList<E> items;
public Stack() { // default constructor; creates an empty stack
    items = new ArrayList<E>(); // initial capacity is 10
}
public Stack(int initialCapacity) {
//one argument constructor, creates a stack with initial capacity  initialCapacity
    items = new ArrayList<E>(initialCapacity);
}
public void push(E x) {
    items.add(x);  //uses the ArrayList method add(E o)
}
public E pop() {
    if (empty())  // determine whether or not there is an item to remove
        return null;
    return items.remove(items.size()-1); //uses the ArrayList method remove(int n)
}
public boolean empty() {
    return items.isEmpty();//uses the ArrayList method isEmpty()
}
public int size() {
    return items.size();  //uses the ArayList method size()
}
public E peek() {
    if (empty()) // determine whether or not there is an item on the stack
        return null;
    return items.get(items.size()-1); //uses the ArrayList method get(int i)
}
public void PrintAndEmpty()
{
     // I want to print then empty the stack here, not in the main method.
}

主要方法

 public static void main (String[] args)  // for demonstration only
 {
     Stack<Student> s = new Stack<Student>();
      // push five Student references onto s
      s.push(new Student("Spanky", "1245"));
      s.push(new Student("Alfalfa", "1656"));
      s.push(new Student("Darla", " 6525"));
      s.push(new Student("Stimie", "1235"));
      s.push(new Student("Jackie", "3498"));

      // The data below is what I am trying to put in the PrintAndEmpty method

      while(!s.empty())
      System.out.println(s.pop().getName());
      System.out.println();
      System.out.println("The size of the stack is now "+s.size());
 }

测试用学生班:

 public class Student
 {
 private String name;
 private String id;
 public Student()
 {
      name = "";
      id = "";
 }
 public Student (String n, String idNum)
 {
      name = n;
      id = idNum;
 }
 public String getName()
 {
      return name;
 }
 public String getID()
 {
      return id;
 }
 public void setName(String n)
 {
      name = n;
 }
 public void setID( String idNum)
 {
      id = idNum;
 }
 public boolean equals(Object o) // name and id are the same
 {
      return (  (((Student)o).name).equals(name)  &&
       (((Student)o).id).equals(id)   );
 }

}

我完全没有办法把它发挥作用。如果有人有什么建议,请告诉我。我将不胜感激!

不确定为什么要这样做,但以下是如何做到的:

// PrintAndEmpty 'this' stack.
public void PrintAndEmpty()
{
   // The condition to check - e.g. 'this' stack.
   while(!this.empty()) {
       // Pop from the stack - e.g. 'this' stack.
       System.out.println(this.pop().getName());
   }
}

最新更新