|
2 | 2 |
|
3 | 3 | import java.util.ArrayList;
|
4 | 4 |
|
| 5 | +/** |
| 6 | + * This class implements a GenericArrayListQueue. |
| 7 | + * <p> |
| 8 | + * A GenericArrayListQueue data structure functions the same as any specific-typed queue. |
| 9 | + * The GenericArrayListQueue holds elemets of types to-be-specified at runtime. |
| 10 | + * The elements that are added first are the first to be removed (FIFO) |
| 11 | + * New elements are added to the back/rear of the queue. |
| 12 | + * |
| 13 | + */ |
5 | 14 | public class GenericArrayListQueue<T> {
|
| 15 | + /** |
| 16 | + * The generic ArrayList for the queue |
| 17 | + * T is the generic element |
| 18 | + */ |
6 | 19 | ArrayList<T> _queue = new ArrayList<T>();
|
7 | 20 |
|
| 21 | + /** |
| 22 | + * Checks if the queue has elements (not empty) |
| 23 | + * |
| 24 | + * @return True if the queue has elements. False otherwise. |
| 25 | + */ |
8 | 26 | private boolean hasElements() {
|
9 | 27 | return !_queue.isEmpty();
|
10 | 28 | }
|
11 | 29 |
|
| 30 | + /** |
| 31 | + * Checks what's at the front of the queue |
| 32 | + * |
| 33 | + * @return If queue is not empty, element at the front of the queue. Otherwise, null |
| 34 | + */ |
12 | 35 | public T peek() {
|
13 | 36 | T result = null;
|
14 | 37 | if(this.hasElements()) { result = _queue.get(0); }
|
15 | 38 | return result;
|
16 | 39 | }
|
17 | 40 |
|
| 41 | + /** |
| 42 | + * Inserts an element of type T to the queue. |
| 43 | + * |
| 44 | + * @param element of type T to be added |
| 45 | + * @return True if the element was added successfully |
| 46 | + */ |
18 | 47 | public boolean add(T element) {
|
19 | 48 | return _queue.add(element);
|
20 | 49 | }
|
21 | 50 |
|
| 51 | + /** |
| 52 | + * Retrieve what's at the front of the queue |
| 53 | + * |
| 54 | + * @return If queue is not empty, element retrieved. Otherwise, null |
| 55 | + */ |
22 | 56 | public T poll() {
|
23 | 57 | T result = null;
|
24 | 58 | if(this.hasElements()) { result = _queue.remove(0); }
|
25 | 59 | return result;
|
26 | 60 | }
|
27 | 61 |
|
| 62 | + /** |
| 63 | + * Main method |
| 64 | + * |
| 65 | + * @param args Command line arguments |
| 66 | + */ |
28 | 67 | public static void main(String[] args) {
|
29 | 68 | GenericArrayListQueue<Integer> queue = new GenericArrayListQueue<Integer>();
|
30 | 69 | System.out.println("Running...");
|
|
0 commit comments