Junior — Middle
What are the advantages and disadvantages of using ArrayList for storing elements?
sobes.tech AI
Answer from AI
Advantages of ArrayList:
- Dynamic size: ArrayList automatically increases its size when new elements are added.
- Fast access by index: access to elements by index occurs in constant time O(1).
- Ease of use: many built-in methods for working with the collection.
Disadvantages of ArrayList:
- Slow insertion/removal in the middle of the list: insertions and deletions, except at the end, require shifting elements, which takes O(n).
- Cost of resizing: when the internal array is full, it is copied to a larger array, which can be time-consuming.
- Not thread-safe: for multi-threaded access, additional synchronization is required.
Example usage:
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println(list.get(0)); // Outputs "Java"