集册 Java实例教程 原始类型测试程序。

原始类型测试程序。

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

362
原始类型测试程序。
/**
n o w    j a v a  . c o m 提供 
**/

import java.util.ArrayList;


class EmptyStackException extends RuntimeException

{

   // no-argument constructor

   public EmptyStackException()

   {

      this("Stack is empty");

   } 


   // one-argument constructor

   public EmptyStackException(String exception)

   {

      super(exception);

   } 

}

class Stack<T>  

{/*来 自 N  o w  J a v a . c o m*/

   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

   }


   // 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); 

   }

}


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};


      // Stack of raw types assigned to Stack of raw types variable

      Stack rawTypeStack1 = new Stack(5); 


      // Stack<Double> assigned to Stack of raw types variable

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


      // Stack of raw types assigned to Stack<Integer> variable

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


      testPush("rawTypeStack1", rawTypeStack1, doubleElements);

      testPop("rawTypeStack1", rawTypeStack1);

      testPush("rawTypeStack2", rawTypeStack2, doubleElements);

      testPop("rawTypeStack2", rawTypeStack2);

      testPush("integerStack", integerStack, integerElements);

      testPop("integerStack", integerStack);

   }


   // generic method pushes elements onto stack

   private 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 stack

   private static <T> void testPop(
展开阅读全文