@@ -26,25 +26,42 @@ public int getSize() {
2626 return this .size ;
2727 }
2828
29+ /** Shrinks the capacity of the underlying fixed-size array to free unused memory. */
30+ public void shrinkSize () {
31+ T [] newArray = (T []) new Object [this .size ];
32+ for (int i = 0 ; i < this .size ; i ++) newArray [i ] = this .array [i ];
33+ this .array = newArray ;
34+ }
35+
36+ /** Doubles the capacity of the underlying fixed-size array. */
37+ public void growSize () {
38+ T [] newArray = (T []) new Object [this .array .length * 2 ];
39+ for (int i = 0 ; i < this .size ; i ++) newArray [i ] = this .array [i ];
40+ this .array = newArray ;
41+ }
42+
2943 /**
3044 * Adds a new element to the end of this dynamic array.
3145 *
3246 * @param e the new element to be added to the end
3347 */
3448 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-
49+ if (this .size + 1 > this .array .length ) this .growSize ();
4550 this .array [this .size ++] = e ;
4651 }
4752
53+ /**
54+ * Adds a new element at the specified index in this dynamic array.
55+ *
56+ * @param e the new element to be added at the specified index
57+ * @param index the index to add the new element at
58+ */
59+ public void add (T e , int index ) {
60+ if (this .size + 1 > this .array .length ) this .growSize ();
61+ for (int i = this .size ++; i > index ; i --) this .array [i ] = this .array [i - 1 ];
62+ this .array [index ] = e ;
63+ }
64+
4865 /** Removes the last element in this dynamic array. */
4966 public void remove () {
5067 this .array [--this .size ] = null ;
@@ -70,4 +87,14 @@ public void removeAt(int index) {
7087 public T getAt (int index ) {
7188 return (T ) this .array [index ];
7289 }
90+
91+ /**
92+ * Prints elements in the specified dynamic array line-by-line.
93+ *
94+ * @param array the dynamic array to be printed
95+ */
96+ public static void printDynamicArray (DynamicArray array ) {
97+ for (int i = 0 ; i < array .getSize (); i ++)
98+ System .out .println (array .getAt (i ));
99+ }
73100}
0 commit comments