ArrayList
ArrayList is one of the most commonly used implementations of the List interface. It stores elements in a resizable array internally, growing automatically as more elements are added.
1. What is ArrayList?
ArrayList is one of the most commonly used implementations of the List interface. It stores elements in a resizable array internally, growing automatically as more elements are added.
2. Why is it used?
Unlike a normal array, ArrayList can grow or shrink as needed, and it comes with many built-in methods for adding, removing, and searching elements, making everyday list operations much simpler.
3. Real-Life Example
Think of an expandable file folder that automatically adds more sections as you keep adding documents, instead of being limited to a fixed number of sections from the start.
4. Syntax
javaArrayList<DataType> listName = new ArrayList<>();
5. Example Program
javaimport java.util.ArrayList; public class ArrayListDemo { public static void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); numbers.remove(0); System.out.println(numbers); } }
Output:
[20]6. Key Points to Remember
ArrayListis best when frequent reading/searching is needed, since it offers fast index-based access.- Adding or removing elements from the middle of a large
ArrayListcan be slower, since remaining elements need to shift. ArrayListis not synchronized, so it is not automatically safe to use across multiple threads at once.