Creating a Dynamic Array in Java
Arrays are linear data structures which means that similar types of elements will be inserted as known in a continuous manner. Now as we know there is an issue with arrays that size needs to be specified at the time of declaration or taken from the user in java which constricts ourselves. Hence, there arise dynamic arrays in java in which entries can be added as the array increases its size as it is full. The size of the new array increases to double the size of the original array. Now all elements are retained in a new array which is in specified array domain size and the rest are added after them in the newly formed array. This array keeps on growing dynamically.
- First, we declared an array of types int with the private access specifier.
- Declare the count variable.
- Create a constructor that initializes the array of the given length.
- Here the magic comes with the method insert.
- First, before we insert the value it checks for the length of the array and count variable if both are of the same size then the array is said to be full.
- Then we create a new array whose size is twice the size of the previous array.
- Just initialized the new array with the previous array and reinitialized it back to the previous array.
Implementation: Creating an Array class that declares the int arr and int count. We just created an array whenever the array is full the array will be resized.
10 30 40 50
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.