Java CheatSheet

Sorting

Arrays.sort()

Array TypeAlgorithmAverage TimeWorst TimeSpaceStableIn-Place
Primitives (int[], double[], etc.)Dual-Pivot QuicksortO(n log n)O(n²)O(log n)❌ No✅ Yes
Objects (String[], Integer[], custom classes)TimSortO(n log n)O(n log n)O(n)✅ Yes❌ No

Data Structures

Queue

A Queue in Java is a FIFO (First-In-First-Out) data structure — elements are added at the rear and removed from the front. It’s defined in the java.util package and is part of the Java Collections Framework.

ImplementationBacking StructureNotes
LinkedListDoubly-linked listSimple, general-purpose, O(1) enqueue/dequeue
ArrayDequeResizable circular arrayFaster than LinkedList (preferred)
PriorityQueueHeap-basedOrders by priority instead of FIFO
ConcurrentLinkedQueueLock-free linked nodesFor multi-threaded use
MethodDescriptionBehavior if empty/fullTime Complexity
offer(E e)Insert at tailReturns false if fullO(1)
add(E e)Insert at tailThrows IllegalStateException if fullO(1)
poll()Remove and return headReturns null if emptyO(1)
remove()Remove and return headThrows NoSuchElementException if emptyO(1)
peek()View head without removingReturns null if emptyO(1)
element()View head without removingThrows NoSuchElementException if emptyO(1)
isEmpty()Check if queue is emptyO(1)
size()Number of elementsO(1)
import java.util.*;

public class QueueExample {
    public static void main(String[] args) {
        Queue<Integer> q = new ArrayDeque<>();

        // Enqueue elements
        q.offer(10);
        q.offer(20);
        q.offer(30);

        // Peek at the front
        System.out.println("Front: " + q.peek());  // 10

        // Dequeue elements
        while (!q.isEmpty()) {
            System.out.println("Processing: " + q.poll());
        }
    }
}

Hash Set

FeatureDescription
Packagejava.util
ImplementsSet<E>
Backed byHashMap<E, Object> (values stored as a dummy constant PRESENT)
OrderingUnordered (no guarantee of iteration order)
Allows Duplicates❌ No
Allows Null✅ Yes (only one null element)
Thread-Safe❌ No (wrap with Collections.synchronizedSet() or use ConcurrentHashMap-based set)
OperationMethodAvg TimeWorst Case*Description
Addadd(E e)O(1)O(n)Adds element if absent
Removeremove(Object o)O(1)O(n)Removes if present
Containscontains(Object o)O(1)O(n)Checks existence
Sizesize()O(1)O(1)Number of elements
Iterateiterator()O(n)O(n)Iterate all
Clearclear()O(n)O(n)Removes all elements

Backed by a HashMap<E, Object>.

Every HashSet element is a key in the internal map; the value is a dummy Object constant.

Uses:

hashCode() → compute hash bucket

equals() → collision resolution

From Java 8 onward, when buckets become large (>8 entries), the internal list converts to a balanced tree → improves worst-case from O(n) → O(log n).

import java.util.*;

public class HashSetDemo {
    public static void main(String[] args) {
        Set<String> countries = new HashSet<>();

        // Add elements
        countries.add("Japan");
        countries.add("USA");
        countries.add("India");
        countries.add("USA"); // duplicate ignored

        // Check existence
        System.out.println(countries.contains("India")); // true

        // Remove
        countries.remove("Japan");

        // Iterate
        for (String c : countries) {
            System.out.println(c);
        }

        // Size
        System.out.println("Size: " + countries.size());
    }
}

Use when you only care about uniqueness (not ordering).

⚠️ For predictable order, use:

  • LinkedHashSet → preserves insertion order.
  • TreeSet → sorted order (O(log n) ops).

⚙️ Choose initial capacity wisely if large inserts are expected:

new HashSet&lt;>(expectedSize * 4 / 3 + 1);

Always implement hashCode() and equals() consistently in custom classes.

Stack

OperationMethodComplexityDescription
Pushpush(E e)O(1)Add item to top
Poppop()O(1)Remove and return top
Peekpeek()O(1)Return top without remove
Searchsearch(Object o)O(n)1-based position from top
Emptyempty()O(1)Check if empty
import java.util.Stack;

Stack<Integer> stack = new Stack<>();

stack.push(10);   // push element
stack.push(20);
stack.pop();      // removes and returns top -> 20
stack.peek();     // returns top without removing -> 10
stack.empty();    // true if stack is empty
stack.size();     // number of elements
ArrayDeque
  • Resizable array–based double-ended queue.
  • Supports LIFO (stack) and FIFO (queue) operations.
  • Non-blocking and non-thread-safe, but faster than Stack or LinkedList.
  • Introduced in Java 6.
Deque<String> stack = new ArrayDeque<>();

stack.push("A");
stack.push("B");
stack.push("C");

System.out.println(stack.pop());  // C
System.out.println(stack.peek()); // B
System.out.println(stack.size()); // 2
Java CheatSheet

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top