Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

Collections in Java ArrayList, HashMap, LinkedList: Tutorial, Examples, FAQs & Interview Tips

Collections Hierarchy

Collections Framework Hierarchy
java.util.Collection (interface)
├── List (interface) - ordered, allows duplicates
│   ├── ArrayList      - dynamic array, fast random access
│   ├── LinkedList     - doubly-linked list, fast insert/delete
│   └── Vector         - legacy, synchronized
├── Set (interface) - no duplicates
│   ├── HashSet        - unordered, O(1) operations
│   ├── LinkedHashSet  - insertion-ordered
│   └── TreeSet        - sorted (natural or Comparator)
└── Queue (interface)
    ├── LinkedList     - also implements Queue
    └── PriorityQueue  - min-heap by default

java.util.Map (interface) - key-value pairs
├── HashMap            - unordered, O(1) operations
├── LinkedHashMap      - insertion-ordered
└── TreeMap            - sorted by key

List - ArrayList & LinkedList

ArrayList & LinkedList
import java.util.*;

public class ListDemo {
    public static void main(String[] args) {
        // ArrayList - backed by a dynamic array
        List<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Banana");
        fruits.add("Cherry");
        fruits.add(1, "Blueberry");  // insert at index 1

        System.out.println(fruits);           // [Apple, Blueberry, Banana, Cherry]
        System.out.println(fruits.get(2));    // Banana
        System.out.println(fruits.size());    // 4
        fruits.remove("Banana");
        System.out.println(fruits.contains("Apple"));  // true

        // Iterate with Iterator
        Iterator<String> it = fruits.iterator();
        while (it.hasNext()) {
            System.out.print(it.next() + " ");
        }
        System.out.println();

        // Sort
        Collections.sort(fruits);
        System.out.println(fruits);  // [Apple, Blueberry, Cherry]

        // LinkedList - efficient insert/delete at both ends
        LinkedList<Integer> deque = new LinkedList<>();
        deque.addFirst(1);
        deque.addLast(2);
        deque.addFirst(0);
        System.out.println(deque);         // [0, 1, 2]
        System.out.println(deque.peekFirst());  // 0
        deque.pollFirst();
        System.out.println(deque);         // [1, 2]
    }
}

Set & Map

HashSet, TreeSet, HashMap, TreeMap
import java.util.*;

public class SetMapDemo {
    public static void main(String[] args) {
        // HashSet - no duplicates, unordered
        Set<String> set = new HashSet<>();
        set.add("Java"); set.add("Python"); set.add("Java");  // duplicate ignored
        System.out.println(set.size());  // 2

        // TreeSet - sorted automatically
        Set<Integer> sorted = new TreeSet<>(Arrays.asList(5, 1, 3, 2, 4));
        System.out.println(sorted);  // [1, 2, 3, 4, 5]

        // HashMap - key-value pairs, unordered
        Map<String, Integer> scores = new HashMap<>();
        scores.put("Alice", 95);
        scores.put("Bob",   87);
        scores.put("Carol", 92);
        scores.put("Alice", 98);  // overwrites previous value

        System.out.println(scores.get("Alice"));       // 98
        System.out.println(scores.containsKey("Bob")); // true
        System.out.println(scores.getOrDefault("Dave", 0));  // 0

        // Iterate over Map entries
        for (Map.Entry<String, Integer> entry : scores.entrySet()) {
            System.out.println(entry.getKey() + " -> " + entry.getValue());
        }

        // TreeMap - sorted by key
        Map<String, Integer> treeMap = new TreeMap<>(scores);
        System.out.println(treeMap);  // {Alice=98, Bob=87, Carol=92}
    }
}
Key Takeaways
  • ArrayList is backed by a dynamic array - O(1) get/set, O(n) insert/delete in the middle.
  • LinkedList is backed by a doubly-linked list - O(1) insert/delete at ends, O(n) random access.
  • HashMap stores key-value pairs with O(1) average get/put. Not thread-safe - use ConcurrentHashMap for threads.
  • HashSet is backed by a HashMap - O(1) add/contains/remove. Does not allow duplicates.
  • TreeMap and TreeSet maintain sorted order - O(log n) operations.
  • Use ArrayList by default; switch to LinkedList only when you need frequent insertions at both ends.
  • Always specify the generic type: List<String> not raw List.
Common Mistakes to Avoid
WRONG List list = new ArrayList()
RIGHT List<String> list = new ArrayList<>()
Always use generics to get compile-time type safety and avoid ClassCastException at runtime.
WRONG for(int i=0; i<list.size(); i++) list.remove(i)
RIGHT Iterator<String> it = list.iterator(); while(it.hasNext()){ it.next(); it.remove(); }
Removing elements while iterating with index causes ConcurrentModificationException. Use Iterator.remove() instead.
WRONG HashMap<String,Integer> map = new HashMap<>(); map.get("key") + 1
RIGHT map.getOrDefault("key", 0) + 1
map.get() returns null for missing keys. Use getOrDefault() to avoid NullPointerException.

Frequently Asked Questions

ArrayList uses a dynamic array - fast random access O(1) but slow insert/delete in middle O(n). LinkedList uses doubly-linked nodes - fast insert/delete at ends O(1) but slow random access O(n). Use ArrayList for most cases.

HashMap is not synchronized (not thread-safe) and allows one null key. Hashtable is synchronized (thread-safe) but slower, and does not allow null keys. For thread safety, use ConcurrentHashMap instead of Hashtable.

HashMap uses an array of buckets. The key's hashCode() determines the bucket index. If multiple keys hash to the same bucket (collision), they are stored in a linked list (or red-black tree in Java 8+ when size > 8).

Comparable defines the natural ordering of a class via compareTo() - the class itself implements it. Comparator defines an external ordering via compare() - useful when you cannot modify the class or need multiple sort orders.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.