Sobes.tech
Junior

What are the implementations of lists in Java?

sobes.tech AI

Answer from AI

In the Java Collections Framework, there are several main implementations of the List interface:

  • ArrayList: A dynamic array. Provides fast access to elements by index, as it is an array. Inserting and deleting elements in the middle of the list can be slow due to the need to shift elements. Stores elements in contiguous memory cells.

    // Creating ArrayList
    List<String> arrayList = new ArrayList<>();
    arrayList.add("Element 1");
    String element = arrayList.get(0); // Fast access by index
    
  • LinkedList: A doubly linked list. Each element stores references to the previous and next elements. Inserting and deleting elements in the middle of the list is fast, as it only requires changing references. Access to elements by index is slow, as it requires traversing the list from the beginning or end.

    // Creating LinkedList
    List<String> linkedList = new LinkedList<>();
    linkedList.add("Element A");
    linkedList.add("Element B");
    linkedList.remove(0); // Fast removal of element
    
  • Vector: A synchronized version of ArrayList. Thread-safe but less performant due to synchronization of all operations. Usually, ArrayList is preferred in single-threaded applications or Collections.synchronizedList() for thread safety when needed.

    // Creating Vector
    List<Integer> vector = new Vector<>();
    vector.add(10); // Thread-safe operation
    
  • Stack: A subclass of Vector implementing a "stack" data structure (LIFO — Last-In, First-Out). Provides push() methods to add elements and pop() to remove the last added element.

    // Creating Stack
    Stack<String> stack = new Stack<>();
    stack.push("First");
    stack.push("Second");
    String lastElement = stack.pop(); // Outputs "Second"
    
  • CopyOnWriteArrayList: A thread-safe list implementation from the java.util.concurrent package. When the list is modified, a new copy of the underlying array is created, making read operations very fast but write operations (adding, removing, changing) relatively slow, especially with large data volumes and frequent modifications. Ideal for scenarios with frequent reads and infrequent writes.

    // Creating CopyOnWriteArrayList
    List<String> copyOnWriteList = new CopyOnWriteArrayList<>();
    copyOnWriteList.add("Item 1"); // Creates a new copy of the array
    

The choice of specific implementation depends on performance requirements for access, insertion, deletion operations, and the need for thread safety.