View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  package org.eclipse.aether.util.graph.visitor;
20  
21  import java.util.AbstractList;
22  import java.util.NoSuchElementException;
23  import java.util.RandomAccess;
24  
25  /**
26   * A non-synchronized stack with a non-modifiable list view which starts at the top of the stack. While
27   * {@code LinkedList} can provide the same behavior, it creates many temp objects upon frequent pushes/pops.
28   */
29  class Stack<E> extends AbstractList<E> implements RandomAccess {
30  
31      @SuppressWarnings("unchecked")
32      // CHECKSTYLE_OFF: MagicNumber
33      private E[] elements = (E[]) new Object[96];
34      // CHECKSTYLE_ON: MagicNumber
35  
36      private int size;
37  
38      public void push(E element) {
39          if (size >= elements.length) {
40              @SuppressWarnings("unchecked")
41              E[] tmp = (E[]) new Object[size + 64];
42              System.arraycopy(elements, 0, tmp, 0, elements.length);
43              elements = tmp;
44          }
45          elements[size++] = element;
46      }
47  
48      public E pop() {
49          if (size <= 0) {
50              throw new NoSuchElementException();
51          }
52          return elements[--size];
53      }
54  
55      public E peek() {
56          if (size <= 0) {
57              return null;
58          }
59          return elements[size - 1];
60      }
61  
62      @Override
63      public E get(int index) {
64          if (index < 0 || index >= size) {
65              throw new IndexOutOfBoundsException("Index: " + index + ", Size: " + size);
66          }
67          return elements[size - index - 1];
68      }
69  
70      @Override
71      public int size() {
72          return size;
73      }
74  }