System.out.println("Array lookup: O(1)"); System.out.println("LinkedList lookup: O(n)"); System.out.println("HashMap lookup: O(1) average, O(n) worst");
Arrays provide direct access by index, so lookup is O(1). Linked lists require traversal, so lookup is O(n). Hash maps use hashing, giving average O(1) lookup but worst case O(n) if many collisions occur.
Hash maps provide average constant time lookup by key, making them ideal for frequent lookups when order is not important.
class Node { int val; Node next; Node(int v) { val = v; next = null; } } Node head = new Node(10); head.next = new Node(20); head.next.next = new Node(30); Node current = head; boolean found = false; while (current != null) { if (current.val == 20) { found = true; break; } current = current.next; } System.out.println(found ? "Found 20" : "Not Found");
The code traverses the linked list and finds the value 20, so it prints "Found 20".
When many keys hash to the same bucket, the hash map handles collisions by chaining (linked list) or tree structures, causing lookup to degrade to O(n) in worst case.
Hash maps provide average O(1) lookup and insertion, making them suitable for large data sets with frequent lookups and occasional insertions when order is not important.
