Junior — Middle
What type of list should be used if you need to frequently retrieve elements by their index?
sobes.tech AI
Answer from AI
For frequent retrieval of elements by their index in Java, it is better to use the ArrayList class. This is because ArrayList is implemented based on an array, and access to an element by index occurs in O(1) time. Unlike LinkedList, where accessing by index requires traversing the elements via links, which takes O(n).
Example of using ArrayList:
List<String> list = new ArrayList<>();
list.add("First");
list.add("Second");
String element = list.get(1); // Fast access by index