Junior — Middle
What type of collection is best suited for efficiently adding elements in the middle of the structure?
sobes.tech AI
Answer from AI
For efficient insertion of elements into the middle of a structure in Java, the LinkedList collection is the best choice.
LinkedList implements a doubly linked list, which allows inserting elements anywhere in the list in O(1) time if there is a reference to the desired node. Unlike ArrayList, where inserting in the middle requires shifting elements and takes O(n).
Example of using LinkedList:
import java.util.LinkedList;
LinkedList<String> list = new LinkedList<>();
list.add("A");
list.add("B");
list.add("D");
// Insert "C" at position 2 (between B and D)
list.add(2, "C");
System.out.println(list); // [A, B, C, D]
If you need to access elements by index frequently, keep in mind that LinkedList has O(n) access time, unlike ArrayList with O(1).