Sobes.tech
Junior — Middle

Can you name different ways to implement the List interface in Java?

sobes.tech AI

Answer from AI

In Java, the List interface can be implemented in various ways depending on performance and functionality requirements:

  • ArrayList — based on an array, provides fast access by index, but slow inserts and deletions in the middle of the list.

  • LinkedList — implemented as a doubly linked list, efficient for inserts and deletions anywhere, but slower for access by index.

  • CopyOnWriteArrayList — thread-safe implementation based on copying the array during modifications, suitable for scenarios with frequent reads and infrequent modifications.

  • Stack — inherits from Vector, implements a stack data structure (LIFO), although nowadays Deque is more commonly used.

  • Vector — similar to ArrayList but synchronized, making it less efficient in single-threaded scenarios.

Example of using ArrayList:

List<String> list = new ArrayList<>();
list.add("Example");
System.out.println(list.get(0));

The choice of implementation depends on specific performance and thread-safety requirements.