List ArrayList and LinkedList

ArrayList Operations

Example

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<String> cart = new ArrayList<>();
        cart.add("Rice");
        cart.add("Dal");
        cart.add("Oil");
        cart.add(1, "Sugar");                // insert at index 1
        System.out.println(cart);

        System.out.println("First: " + cart.get(0));
        cart.set(2, "Moong Dal");            // replace
        cart.remove("Oil");                  // remove by value
        System.out.println(cart + " size=" + cart.size());

        System.out.println("Has Rice? " + cart.contains("Rice"));
        System.out.println("Index of Sugar: " + cart.indexOf("Sugar"));
        cart.add("Rice");                    // duplicates allowed
        System.out.println(cart);

        for (int i = 0; i < cart.size(); i++) {
            System.out.println((i + 1) + ". " + cart.get(i));
        }
    }
}

Output

[Rice, Sugar, Dal, Oil]
First: Rice
[Rice, Sugar, Moong Dal] size=3
Has Rice? true
Index of Sugar: 1
[Rice, Sugar, Moong Dal, Rice]
1. Rice
2. Sugar
3. Moong Dal
4. Rice

ArrayList vs LinkedList

OperationArrayListLinkedList
Internal structureresizable arraydoubly linked nodes
get(index)O(1) fastO(n) slow
Add at endO(1) amortisedO(1)
Insert/remove in middleO(n) (shifts elements)O(1) once at the node (but finding it is O(n))
Memorycompactextra pointers per element
Usedefault choice (95% of cases)rarely; ArrayDeque is better for queues

remove(int) vs remove(Object)

Example

With List<Integer>, remove(1) removes the element at index 1, not the value 1.

import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = new ArrayList<>(List.of(10, 1, 20, 1));
        nums.remove(1);                      // removes index 1 -> the value 1
        System.out.println(nums);
        nums.remove(Integer.valueOf(20));    // removes the value 20
        System.out.println(nums);
    }
}

Output

[10, 20, 1]
[10, 1]