### Introduction to Dynamic Array - The Coding Shala

Home >> Data Structures >> Introduction to Dynamic Array

## Introduction to Dynamic Array

Arrays can be dynamic in size or I can say sometimes we don't know the size of an array at the starting point. In this case, we need to declare an array of variable size. For that, we use ArrayList in Java(vector in C++).

NOTE: ArrayList is a part of Collections.

The following example explains the basics operation of dynamic Array or ArrayList:

```import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

//ArrayList Example
public class Main{
public static void main(String[] args) {
//initializing an ArrayList
ArrayList<Integer> arr0 = new ArrayList<>();

//inserting elements into arrayList
for(int i=1; i<=5;i++) {
}

//accessing elements from an arrayList
for(int i=0;i<5;i++) {
System.out.print(arr0.get(i)+" ");  //index starts with 0
}
System.out.println();

//get length of an arraylist
System.out.println("Size of arr0 is: "+arr0.size());

//modifying element
//set(index, element);

arr0.set(0, 10);
arr0.set(3, 15);

for(int i : arr0) System.out.print(i+" ");
System.out.println();

//remove an element
arr0.remove(arr0.size()-1); //remove last element
for(int i : arr0) System.out.print(i+" ");
System.out.println();

//sorting an arraylist
System.out.println("After sorting arr0");
Collections.sort(arr0);
System.out.println(arr0);

Integer[] a = {5,2,3,1,3};
ArrayList<Integer> arr2;
arr2 = new ArrayList<>(Arrays.asList(a));
System.out.println("ArrayList arr2 is: "+arr2);

//copying an arrayList
ArrayList<Integer> arr3 = arr2;  //here arr3 is just reference of arr2
ArrayList<Integer> arr4 = new ArrayList<>(arr2); //this new copy of arr2
System.out.println("arraylist arr3 is: "+arr3);  //same as arr2
System.out.println("arraylist arr2 is: "+arr2);
System.out.println("arraylist arr4 is: "+arr4);
}
}
```
Output:

```1 2 3 4 5
Size of arr0 is: 5
21 10 2 3 15 5
21 10 2 3 15
After sorting arr0
[2, 3, 10, 15, 21]
ArrayList arr2 is: [5, 2, 3, 1, 3]
arraylist arr3 is: [5, 2, 3, 1, 3, 40]
arraylist arr2 is: [5, 2, 3, 1, 3, 40]
arraylist arr4 is: [5, 2, 3, 1, 3, 30]
```

Other Posts You May Like