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