Creating a Dynamic Array in Java
Last Updated :
30 Jun, 2021
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.
Procedure:
- 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.
Example
Java
class Array {
private int arr[];
private int count;
public Array( int length) { arr = new int [length]; }
public void printArray()
{
for ( int i = 0 ; i < count; i++) {
System.out.print(arr[i] + " " );
}
}
public void insert( int element)
{
if (arr.length == count) {
int newArr[] = new int [ 2 * count];
for ( int i = 0 ; i < count; i++) {
newArr[i] = arr[i];
}
arr = newArr;
}
arr[count++] = element;
}
}
public class GFG {
public static void main(String[] args)
{
Array numbers = new Array( 3 );
numbers.insert( 10 );
numbers.insert( 30 );
numbers.insert( 40 );
numbers.insert( 50 );
numbers.printArray();
}
}
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...