集册 Java实例教程 用泛型方法测试泛型堆栈类

用泛型方法测试泛型堆栈类

欢马劈雪     最近更新时间:2020-01-02 10:19:05

556
用泛型方法测试泛型堆栈类
/** 来 自 时   代     Java  公  众  号 - nowjava.com**/

import java.util.ArrayList;


class Stack<T>  

{

   private final ArrayList<T> elements; // ArrayList stores stack elements


   // no-argument constructor creates a stack of the default size

   public Stack()

   {

      this(10); // default stack size

   } 


   // constructor creates a stack of the specified number of elements

   public Stack(int capacity)

   {

      int initCapacity = capacity > 0 ? capacity : 10; // validate

      elements = new ArrayList<T>(initCapacity); // create ArrayList

   }/*来自 时代Java公众号*/


   // push element onto stack

   public void push(T pushValue)

   {

      elements.add(pushValue); // place pushValue on Stack

   } 


   // return the top element if not empty; else throw EmptyStackException

   public T pop()

   {

      if (elements.isEmpty()) // if stack is empty

         throw new EmptyStackException("Stack is empty, cannot pop");


      // remove and return top element of Stack

      return elements.remove(elements.size() - 1); 

   }

}

 class EmptyStackException extends RuntimeException

{

   // no-argument constructor

   public EmptyStackException()

   {

      this("Stack is empty");

   } 


   // one-argument constructor

   public EmptyStackException(String exception)

   {

      super(exception);

   } 

}


public class Main 

{

   public static void main(String[] args) 

   {

      Double[] doubleElements = {1.1, 2.2, 3.3, 4.4, 5.5};

      Integer[] integerElements = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

      

      // Create a Stack<Double> and a Stack<Integer>

      Stack<Double> doubleStack = new Stack<>(5); 

      Stack<Integer> integerStack = new Stack<>(); 


      // push elements of doubleElements onto doubleStack

      testPush("doubleStack", doubleStack, doubleElements);

      testPop("doubleStack", doubleStack); // pop from doubleStack


      // push elements of integerElements onto integerStack

      testPush("integerStack", integerStack, integerElements);

      testPop("integerStack", integerStack); // pop from integerStack

   } 


   // generic method testPush pushes elements onto a Stack

   public static <T> void testPush(String name , Stack<T> stack, 

      T[] elements)

   {

      System.out.printf("%nPushing elements onto %s%n", name);


      // push elements onto Stack

      for (T element : elements)

      {

         System.out.printf("%s ", element);

         stack.push(element); // push element onto stack

      } 

   } 


   // generic method testPop pops elements from a Stack

   public static <T> void testPop(String name, Stack<T
展开阅读全文