|
| 1 | +@SuppressWarnings("unchecked") |
| 2 | +public class DynamicArray<T> { |
| 3 | + private T[] array; // The underlying fixed-size array |
| 4 | + private int size = 0; // The number of elements inside this dynamic array |
| 5 | + |
| 6 | + /** Initializes a new dynamic array with an initial capacity of 10. */ |
| 7 | + public DynamicArray() { |
| 8 | + this.array = (T[]) new Object[10]; |
| 9 | + } |
| 10 | + |
| 11 | + /** |
| 12 | + * Initializes a new dynamic array with the given initial capacity. |
| 13 | + * |
| 14 | + * @param initialCapacity the initial capacity of the new dynamic array |
| 15 | + */ |
| 16 | + public DynamicArray(int initialCapacity) { |
| 17 | + this.array = (T[]) new Object[initialCapacity]; |
| 18 | + } |
| 19 | + |
| 20 | + /** |
| 21 | + * Returns the number of elements in this dynamic array. |
| 22 | + * |
| 23 | + * @return the number of elements in this dynamic array. |
| 24 | + */ |
| 25 | + public int getSize() { |
| 26 | + return this.size; |
| 27 | + } |
| 28 | + |
| 29 | + /** |
| 30 | + * Adds a new element to the end of this dynamic array. |
| 31 | + * |
| 32 | + * @param e the new element to be added to the end |
| 33 | + */ |
| 34 | + public void add(T e) { |
| 35 | + // Create a new fixed-length array with doubled capacity when space is run |
| 36 | + // out |
| 37 | + if (this.size + 1 > this.array.length) { |
| 38 | + T[] newArray = (T[]) new Object[this.array.length * 2]; // double in size |
| 39 | + |
| 40 | + for (int i = 0; i < this.size; i++) newArray[i] = this.array[i]; |
| 41 | + |
| 42 | + this.array = newArray; |
| 43 | + } |
| 44 | + |
| 45 | + this.array[this.size++] = e; |
| 46 | + } |
| 47 | + |
| 48 | + /** Removes the last element in this dynamic array. */ |
| 49 | + public void remove() { |
| 50 | + this.array[--this.size] = null; |
| 51 | + } |
| 52 | + |
| 53 | + /** |
| 54 | + * Removes the element at the specified index in this dynamic array. |
| 55 | + * |
| 56 | + * @param index the index of the element to be removed |
| 57 | + */ |
| 58 | + public void removeAt(int index) { |
| 59 | + // Shift to the right starting at the specified index |
| 60 | + for (int i = index; i < this.size - 1; i++) this.array[i] = this.array[i + 1]; |
| 61 | + |
| 62 | + this.remove(); |
| 63 | + } |
| 64 | + |
| 65 | + /** |
| 66 | + * Returns the element at the specified index in this dynamic array. |
| 67 | + * |
| 68 | + * @param index the index of the element to be returned |
| 69 | + */ |
| 70 | + public T getAt(int index) { |
| 71 | + return (T) this.array[index]; |
| 72 | + } |
| 73 | +} |
0 commit comments