We all know about the basic data structure, which is** Array **pretty well. And in java they are static. It means we have to allocate memory for the array ahead of time. The memory will define the number of elements that the array can hold. But what if we have know idea about the exact number of elements that we are going to insert before hand. Then the best thing is to have a dynamic array.

A dynamic array automatically grows when we try to make an insertion and there is no space left for the new item. A simple dynamic array can be constructed, by using an array of fixed-size. The elements of the array are stored contiguously, for an instance, if it is an integer type array it will take 4 bytes of space per integer element. The remaining positions towards the end are reserved and unused. New elements can be added to the end of the array until the reserved space is fully utilized. If you still need to add up more elements even after that, the array needs to be resized which is a very expensive task. Usually it doubles its size.

Following is the Figure 1, where you can find the Array class, to model a dynamic behavior by using a static array in Java. Basic array operations are implemented below.

public class Array {

		private int[] items;
		private int count;

		public Array(int length) {

			items = new int[length];
		}

		public void print() {

			for(int i=0;i<count;i++) {
				System.out.println(items[i]);
			}
		}

		public void insert(int number) {

			//If an item is added to the end
			items[count]=number;
			count++;

			//If the array is full, resize it
			if(items.length == count) {

				int[] newItems = new int[count*2];

				for(int i=0;i<count;i++) {
					newItems[i]=items[i];
				}

				items=newItems;
			}

		}

		//Delete
		public void removeAt(int index) {

			if(index<0 || index>=count ) {
				throw new IllegalArgumentException();
			}	

			for(int i=index;i<count;i++) {
				items[i]=items[i+1];
			}

			count--;
		}

		//Search
		public int indexOf(int number) {

			for(int i=0;i<count;i++) {
				if(number == items[i]) {
					return i;
				}
			}

			return -1;

		}
	}

#dynamic-array #data-structures #java #arrays

How to Build a Dynamic Array By Using a Static Array in Java
5.15 GEEK