Junior — Middle
What data structures are used for quick addition of elements to the end of a collection?
sobes.tech AI
Answer from AI
For quick addition of elements to the end of a collection in Java, the following data structures are usually used:
- ArrayList — a dynamic array that provides amortized constant time O(1) for adding an element to the end. When the internal array is full, it is expanded.
- LinkedList — a doubly linked list where adding to the end takes constant time O(1), as there is a reference to the last element.
Example of using ArrayList:
List<String> list = new ArrayList<>();
list.add("element");
Example of using LinkedList:
LinkedList<String> linkedList = new LinkedList<>();
linkedList.addLast("element");
The choice depends on performance and memory requirements: ArrayList is faster for random access, LinkedList is better for frequent additions/removals at the beginning or end.