Junior — Middle
What are the ways to implement the List interface in Java and what are their differences?
sobes.tech AI
Answer from AI
In Java, the List interface is implemented by several main classes, each with its own features:
- ArrayList — implemented based on a dynamic array. Fast access by index (O(1)), but insertions and deletions in the middle of the list can be costly (O(n)), as elements are shifted.
- LinkedList — implemented as a doubly linked list. Fast insertion and deletion of elements anywhere in the list (O(1) with a reference), but access by index is slower (O(n)), as it requires traversing the elements.
- Vector — similar to ArrayList but synchronized (thread-safe). Less commonly used in modern applications due to synchronization overhead.
The choice of implementation depends on performance requirements:
- If fast random access and infrequent size changes are needed —
ArrayList. - If frequent insertions/deletions in the middle are needed —
LinkedList. - If thread safety is required —
Vectoror better to useCollections.synchronizedListorCopyOnWriteArrayList.
Example of using ArrayList:
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
System.out.println(list.get(0)); // apple