Skip to content

List

List Interface

Think of List as a well-behaved queue with memory 🎭 It keeps order, allows duplicates, and lets you poke elements by index like a playlist you can rearrange mid-song.


🧩 What is List?

List is part of the Java Collections Framework

List<String> names = new ArrayList<>();

👉 It represents an ordered collection (sequence)


🔑 Key Characteristics

  • Maintains insertion order 📌
  • Allows duplicate elements 🔁
  • Supports index-based access (0,1,2...)
  • Can contain null values

🏗️ Common Implementations

1. ArrayList

Image

Image

Image

Image

Image

List<String> list = new ArrayList<>();
  • Backed by dynamic array
  • Fast for read (O(1))
  • Slow for insert/delete in middle

👉 Best when: frequent reads


2. LinkedList

Image

Image

Image

Image

Image

List<String> list = new LinkedList<>();
  • Uses doubly linked list
  • Fast insert/delete
  • Slow random access

👉 Best when: frequent insert/delete


3. Vector (Legacy)

List<String> list = new Vector<>();
  • Thread-safe (synchronized)
  • Slower performance
  • Rarely used now

4. Stack (Legacy)

Stack<Integer> stack = new Stack<>();
  • Follows LIFO (Last In First Out)

⚙️ Important Methods

List<String> list = new ArrayList<>();

list.add("A");          // add element
list.add(1, "B");       // add at index
list.get(0);            // get element
list.set(0, "Z");       // update
list.remove(1);         // remove
list.contains("Z");     // check
list.size();            // size

🧠 Example with Output

List<String> list = new ArrayList<>();

list.add("Java");
list.add("Python");
list.add("Java");

System.out.println(list);

👉 Output:

id="6b9y7y" [Java, Python, Java]

✔ Order maintained ✔ Duplicate allowed


🔄 ArrayList vs LinkedList (Quick View)

Feature ArrayList 🧱 LinkedList 🔗
Structure Dynamic Array Doubly Linked List
Access Fast ⚡ Slow 🐢
Insert/Delete Slow Fast
Memory Less More

🎯 Interview Nuggets

  • List is interface, not class
  • Default choice → ArrayList
  • Use LinkedList for frequent modifications
  • Vector = legacy (avoid unless needed)

🧠 Memory Trick

List = Ordered + Duplicate + Index access