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 private E[] elements = (E[]) new Object[96];
37
38 private int size;
39
40 public void push( E element )
41 {
42 if ( size >= elements.length )
43 {
44 @SuppressWarnings( "unchecked" )
45 E[] tmp = (E[]) new Object[size + 64];
46 System.arraycopy( elements, 0, tmp, 0, elements.length );
47 elements = tmp;
48 }
49 elements[size++] = element;
50 }
51
52 public E pop()
53 {
54 if ( size <= 0 )
55 {
56 throw new NoSuchElementException();
57 }
58 return elements[--size];
59 }
60
61 public E peek()
62 {
63 if ( size <= 0 )
64 {
65 return null;
66 }
67 return elements[size - 1];
68 }
69
70 @Override
71 public E get( int index )
72 {
73 if ( index < 0 || index >= size )
74 {
75 throw new IndexOutOfBoundsException( "Index: " + index + ", Size: " + size );
76 }
77 return elements[size - index - 1];
78 }
79
80 @Override
81 public int size()
82 {
83 return size;
84 }
85
86 }