Update
use import java.util.ArrayList to work properly
The arrays what we have learned before have a fixed size i.e., we can't add extra elements to that array list. in the above image the array strArray contains three elements we can't add the fourth element (with index 3).
When we try to add this fourth element we will get error but we can but we can replace / overwrite the elements of the array which show in the figure below.
Dynamic Array
But in the dynamic array we can add as many elements we want.
The syntax for the dynamic array is
ArrayList<Data type> Arrayname = new ArrayList<>();
This ArrayList only accept primitive data types like String.
If we want to use this ArrayList for non primitive data types like int, float, double we need to replace them with Integer, Float, Double with capital letters in the starting.
Methods in ArrayLists
ArrayName.add("#") //adds the element to that ArrayList.
ArrayName.add(1,"#") //adds the element to that ArrayList at index no. 1
ArrayName.get(1) // it get the value at index 1
ArrayName.remove(0) // it removes the value at index 0
ArrayName.remove(0) // it removes the value at index 0
ArrayName.contains("#") // it checks whether the value we given is exist in that ArrayList or not. It returns true or false.
ArrayName.clear() // it clears all the values of array.
0 Comments