Data Structures in Java

Here’s a quick overview of basic data structures that form the foundation of computer science and programming:


1. Array

  • Definition: A collection of elements stored in contiguous memory locations.

  • Key Points:

    • Fixed size.

    • Index-based access (fast lookup).

    • Insertion/deletion can be costly.

  • Example (Java):

    int[] arr = {10, 20, 30, 40};
    System.out.println(arr[2]); // Output: 30
    

2. Linked List

  • Definition: A collection of nodes, where each node contains data and a pointer to the next node.

  • Types: Singly Linked List, Doubly Linked List, Circular Linked List.

  • Key Points:

    • Dynamic size.

    • Easy insertion/deletion.

    • Sequential access (slower lookup than arrays).

  • Example (Node Structure in Java):

    class Node {
        int data;
        Node next;
        Node(int d) { data = d; next = null; }
    }
    

3. Stack

  • Definition: A linear data structure that follows LIFO (Last In First Out).

  • Key Operations:

    • push() β†’ add element

    • pop() β†’ remove element

    • peek() β†’ view top element

  • Use Cases: Undo operations, expression evaluation, function call stack.

  • Example:

    Stack<Integer> stack = new Stack<>();
    stack.push(10);
    stack.push(20);
    System.out.println(stack.pop()); // Output: 20
    

4. Queue

  • Definition: A linear data structure that follows FIFO (First In First Out).

  • Key Operations:

    • enqueue() β†’ add element

    • dequeue() β†’ remove element

  • Types: Simple Queue, Circular Queue, Priority Queue, Deque.

  • Use Cases: Scheduling, buffering.

  • Example:

    Queue<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.remove()); // Output: 1
    

5. Hash Table / Hash Map

  • Definition: Stores key-value pairs using hashing for fast access.

  • Key Points:

    • Average O(1) lookup and insertion.

    • Collisions handled by chaining or open addressing.

  • Example:

    HashMap<String, Integer> map = new HashMap<>();
    map.put("A", 1);
    map.put("B", 2);
    System.out.println(map.get("A")); // Output: 1
    

6. Tree

  • Definition: Hierarchical structure with nodes; top node is root.

  • Types: Binary Tree, Binary Search Tree (BST), AVL Tree, Heap.

  • Use Cases: Hierarchical data, searching, sorting, parsing expressions.

  • Example (Binary Tree Node in Java):

    class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int x) { val = x; }
    }
    

7. Graph

  • Definition: A collection of nodes (vertices) connected by edges.

  • Types: Directed/Undirected, Weighted/Unweighted, Cyclic/Acyclic.

  • Use Cases: Networking, maps, social networks.

  • Example (Adjacency List):

    Map<Integer, List<Integer>> graph = new HashMap<>();
    graph.put(1, Arrays.asList(2,3));
    graph.put(2, Arrays.asList(1,4));
    
Back to blog

Leave a comment