算法Sedgewick第四版-第1章基础-018一解决不能声明泛型数组的两咱方法(强转或反射)

1.

  1 /******************************************************************************
  2  *  Compilation:  javac ResizingArrayStackWithReflection.java
  3  *  Execution:    java ResizingArrayStackWithReflection < input.txt
  4  *  Dependencies: StdIn.java StdOut.java
  5  *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
  6  *  
  7  *  Stack implementation with a resizing array.
  8  *
  9  *  % more tobe.txt 
 10  *  to be or not to - be - - that - - - is
 11  *
 12  *  % java ResizingArrayStackWithReflection < tobe.txt
 13  *  to be not that or be (2 left on stack)
 14  *
 15  *  Written by Bruno Lehouque.
 16  *
 17  ******************************************************************************/
 18 
 19 import java.lang.reflect.Array;
 20 import java.util.Iterator;
 21 import java.util.NoSuchElementException;
 22 
 23 /**
 24  * A LIFO Stack using a resizeable array.
 25  */
 26 public class ResizingArrayStackWithReflection<Item> implements Iterable<Item> {
 27     
 28     private Class<Item[]> itemArrayClass;
 29     private Item[] array;
 30     private int N = 0;
 31 
 32     public ResizingArrayStackWithReflection(Class<Item[]> itemArrayClass) {
 33         this.itemArrayClass = itemArrayClass;
 34         array = itemArrayClass.cast(Array.newInstance(itemArrayClass.getComponentType(), 1));
 35     }
 36 
 37     /**
 38      * Adds a non-{@code null} element on top of the Stack.
 39      * 
 40      * @param item
 41      *      the element which is to be added to the Stack
 42      * 
 43      * @throws IllegalArgumentException if {@code item} is {@code null}.
 44      */
 45     public void push(Item item) {
 46         if (item == null)
 47             throw new IllegalArgumentException("Cannot add null item.");
 48         if (N == array.length)
 49             resize(array.length * 2);
 50         array[N++] = item;
 51     }
 52 
 53     /**
 54      * Removes and returns the top element of the Stack.
 55      * 
 56      * @return the top element of the Stack
 57      * 
 58      * @throws NoSuchElementException if the Stack is empty
 59      */
 60     public Item pop() {
 61         if (isEmpty())
 62             throw new NoSuchElementException();
 63         Item item = array[--N];
 64         array[N] = null;
 65         if ((N > 0) && (N <= array.length / 4))
 66             resize(array.length / 2);
 67         return item;
 68     }
 69 
 70     /**
 71      * Returns, but doesn't remove, the top element of the Stack.
 72      * 
 73      * @return the top element of the Stack
 74      * 
 75      * @throws NoSuchElementException if the Stack is empty
 76      */
 77     public Item peek() {
 78         if (isEmpty())
 79             throw new NoSuchElementException();
 80         return array[N - 1];
 81     }
 82 
 83     /**
 84      * Returns {@code true} if the Stack is empty.
 85      * 
 86      * @return {@code true} if the Stack is empty
 87      */
 88     public boolean isEmpty() {
 89         return N == 0;
 90     }
 91 
 92     /**
 93      * Returns the size of the Stack.
 94      * 
 95      * @return the size of the Stack
 96      */
 97     public int size() {
 98         return N;
 99     }
100     
101     /**
102      * Returns an iterator which iterates over the Stack from the top element
103      * to the bottom element.
104      * 
105      * @return an iterator which iterates over the Stack from the top element
106      * to the bottom element
107      */
108     public Iterator<Item> iterator() {
109         return new ReverseArrayIterator();
110     }
111 
112     private void resize(int size) {
113         Item[] newarray = itemArrayClass.cast(Array.newInstance(itemArrayClass.getComponentType(), size));
114         for (int i = 0; i < N; i++)
115             newarray[i] = array[i];
116         array = newarray;
117     }
118 
119     private class ReverseArrayIterator implements Iterator<Item> {
120         
121         private int i = N-1;
122 
123         @Override
124         public boolean hasNext() {
125             return i >= 0;
126         }
127 
128         @Override
129         public Item next() {
130             if (!hasNext())
131                 throw new NoSuchElementException();
132             return array[i--];
133         }
134 
135         @Override
136         public void remove() {
137             throw new UnsupportedOperationException("Not supported.");
138         }
139         
140     }
141 
142     /**
143      * Test client (copied from ResizingArrayStack).
144      */
145     public static void main(String[] args) {
146         ResizingArrayStackWithReflection<String> s = new ResizingArrayStackWithReflection<String>(String[].class);
147         while (!StdIn.isEmpty()) {
148             String item = StdIn.readString();
149             if (!item.equals("-")) s.push(item);
150             else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
151         }
152         StdOut.println("(" + s.size() + " left on stack)");
153     }
154 }

 

2.

  1 /******************************************************************************
  2  *  Compilation:  javac ResizingArrayStack.java
  3  *  Execution:    java ResizingArrayStack < input.txt
  4  *  Dependencies: StdIn.java StdOut.java
  5  *  Data files:   http://algs4.cs.princeton.edu/13stacks/tobe.txt
  6  *  
  7  *  Stack implementation with a resizing array.
  8  *
  9  *  % more tobe.txt 
 10  *  to be or not to - be - - that - - - is
 11  *
 12  *  % java ResizingArrayStack < tobe.txt
 13  *  to be not that or be (2 left on stack)
 14  *
 15  ******************************************************************************/
 16 
 17 import java.util.Iterator;
 18 import java.util.NoSuchElementException;
 19 
 20 /**
 21  *  The <tt>ResizingArrayStack</tt> class represents a last-in-first-out (LIFO) stack
 22  *  of generic items.
 23  *  It supports the usual <em>push</em> and <em>pop</em> operations, along with methods
 24  *  for peeking at the top item, testing if the stack is empty, and iterating through
 25  *  the items in LIFO order.
 26  *  <p>
 27  *  This implementation uses a resizing array, which double the underlying array
 28  *  when it is full and halves the underlying array when it is one-quarter full.
 29  *  The <em>push</em> and <em>pop</em> operations take constant amortized time.
 30  *  The <em>size</em>, <em>peek</em>, and <em>is-empty</em> operations takes
 31  *  constant time in the worst case. 
 32  *  <p>
 33  *  For additional documentation,
 34  *  see <a href="http://algs4.cs.princeton.edu/13stacks">Section 1.3</a> of
 35  *  <i>Algorithms, 4th Edition</i> by Robert Sedgewick and Kevin Wayne.
 36  *
 37  *  @author Robert Sedgewick
 38  *  @author Kevin Wayne
 39  */
 40 public class ResizingArrayStack<Item> implements Iterable<Item> {
 41     private Item[] a;         // array of items
 42     private int N;            // number of elements on stack
 43 
 44 
 45     /**
 46      * Initializes an empty stack.
 47      */
 48     public ResizingArrayStack() {
 49         a = (Item[]) new Object[2];
 50         N = 0;
 51     }
 52 
 53     /**
 54      * Is this stack empty?
 55      * @return true if this stack is empty; false otherwise
 56      */
 57     public boolean isEmpty() {
 58         return N == 0;
 59     }
 60 
 61     /**
 62      * Returns the number of items in the stack.
 63      * @return the number of items in the stack
 64      */
 65     public int size() {
 66         return N;
 67     }
 68 
 69 
 70     // resize the underlying array holding the elements
 71     private void resize(int capacity) {
 72         assert capacity >= N;
 73         Item[] temp = (Item[]) new Object[capacity];
 74         for (int i = 0; i < N; i++) {
 75             temp[i] = a[i];
 76         }
 77         a = temp;
 78     }
 79 
 80     /**
 81      * Adds the item to this stack.
 82      * @param item the item to add
 83      */
 84     public void push(Item item) {
 85         if (N == a.length) resize(2*a.length);    // double size of array if necessary
 86         a[N++] = item;                            // add item
 87     }
 88 
 89     /**
 90      * Removes and returns the item most recently added to this stack.
 91      * @return the item most recently added
 92      * @throws java.util.NoSuchElementException if this stack is empty
 93      */
 94     public Item pop() {
 95         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
 96         Item item = a[N-1];
 97         a[N-1] = null;                              // to avoid loitering
 98         N--;
 99         // shrink size of array if necessary
100         if (N > 0 && N == a.length/4) resize(a.length/2);
101         return item;
102     }
103 
104 
105     /**
106      * Returns (but does not remove) the item most recently added to this stack.
107      * @return the item most recently added to this stack
108      * @throws java.util.NoSuchElementException if this stack is empty
109      */
110     public Item peek() {
111         if (isEmpty()) throw new NoSuchElementException("Stack underflow");
112         return a[N-1];
113     }
114 
115     /**
116      * Returns an iterator to this stack that iterates through the items in LIFO order.
117      * @return an iterator to this stack that iterates through the items in LIFO order.
118      */
119     public Iterator<Item> iterator() {
120         return new ReverseArrayIterator();
121     }
122 
123     // an iterator, doesn't implement remove() since it's optional
124     private class ReverseArrayIterator implements Iterator<Item> {
125         private int i;
126 
127         public ReverseArrayIterator() {
128             i = N-1;
129         }
130 
131         public boolean hasNext() {
132             return i >= 0;
133         }
134 
135         public void remove() {
136             throw new UnsupportedOperationException();
137         }
138 
139         public Item next() {
140             if (!hasNext()) throw new NoSuchElementException();
141             return a[i--];
142         }
143     }
144 
145 
146     /**
147      * Unit tests the <tt>Stack</tt> data type.
148      */
149     public static void main(String[] args) {
150         ResizingArrayStack<String> s = new ResizingArrayStack<String>();
151         while (!StdIn.isEmpty()) {
152             String item = StdIn.readString();
153             if (!item.equals("-")) s.push(item);
154             else if (!s.isEmpty()) StdOut.print(s.pop() + " ");
155         }
156         StdOut.println("(" + s.size() + " left on stack)");
157     }
158 }

 

posted @ 2016-04-19 18:29  shamgod  阅读(234)  评论(0编辑  收藏  举报
haha