Sobes.tech
Middle

Tell us about ArrayList: features, initial size, insert and delete operations.

sobes.tech AI

Answer from AI

ArrayList in Java is an implementation of a dynamic array that automatically increases its size when needed.

Features:

  • Allows storing elements in insertion order.
  • Fast access by index (get operation) — O(1).
  • Inserting and removing elements in the middle of the list — O(n), as it requires shifting elements.
  • Not synchronized, so it is not thread-safe without external synchronization.

Initial size: By default, ArrayList is created with an internal array of size 10. When adding elements, if the internal array is full, it increases by approximately 50% of the current size.

Insert and delete operations:

  • Insertion at the end — amortized O(1).
  • Insertion in the middle or beginning — O(n) due to shifting elements.
  • Removal by index — O(n) due to shifting.

Example of creation and usage:

ArrayList<String> list = new ArrayList<>();
list.add("First");
list.add(0, "Zero"); // insert at the beginning
list.remove(1); // remove the second element
String item = list.get(0); // access by index