How to use Java ArrayList: Tutorial with Example
What is ArrayList in Java?
ArrayList is a data structure that can be stretched to accommodate additional elements within itself and shrink back to a smaller size when elements are removed. It is a very important data structure useful in handling the dynamic behavior of elements.
Wondering how ArrayList java could be useful, see the below conversation –
See the following picture of a man stretching an elastic rubber band.
The actual length of the rubber band is much smaller, but when stretched it can extend a lot more than its actual length and can be used to hold/bind much larger objects with it.
Now, consider the next picture, that of a simple rope, it cannot stretch and will have a fixed length.
It can grow as, and when required to accommodate the elements it needs to store and when elements are removed, it can shrink back to a smaller size.
So as our friend has an issue with the array he is using cannot be expanded or made to shrink, we will be using ArrayList.
Arrays are like the rope shown in the above picture; they will have a fixed length, cannot be expanded nor reduced from the original length.
So our stretchable rubber-band is much like the Array List whereas the rope can be considered as the array.
Technically speaking, java Array List is like a dynamic array or a variable-length array.
Let us see and understand the following code snippet that will help you work around with Array List.