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