Mostrando postagens com marcador index. Mostrar todas as postagens
Mostrando postagens com marcador index. Mostrar todas as postagens

HashMap in Java

Let’s break down how HashMap works internally (Java 8+ implementation).


What Is a HashMap?

HashMap<K, V> is a hash table–based implementation of the Map interface.

It stores data as:

key → value

It provides average O(1) time complexity for:

  • put()

  • get()

  • remove()


Core Data Structure

Internally, HashMap uses:

Array of buckets

Each bucket contains:

  • A LinkedList (before Java 8)

  • A LinkedList OR Red-Black Tree (Java 8+)

Structure simplified:

Node<K,V>[] table

Each array index is called a bucket.


How put() Works Internally

When you do:

map.put("apple", 10);

Step 1: Calculate Hash

It calls:

int hash = key.hashCode();

Then applies a hash spreading function:

(hash ^ (hash >>> 16))

This improves distribution.


Step 2: Calculate Bucket Index

index = (n - 1) & hash

Where:

  • n = array length

  • & = bitwise AND (faster than modulo)

This determines where the entry will go.


Step 3: Insert into Bucket

Now 3 cases:

Case 1: Bucket is empty

→ Insert new node.

Case 2: Same key already exists

→ Replace value.

Case 3: Collision (different key, same index)

→ Add node to:

  • LinkedList (if small)

  • Red-Black Tree (if too many collisions)


What Is a Collision?

A collision happens when:

Different keys → Same bucket index

Example:

hash("FB") == hash("Ea")

Both go to same bucket.

HashMap handles collisions by chaining.


Treeification (Java 8 Improvement)

If a bucket has more than:

8 nodes

It converts the linked list into a:

Red-Black Tree

Why?

  • LinkedList lookup = O(n)

  • Red-Black Tree lookup = O(log n)

This prevents performance degradation.


How get() Works

When you call:

map.get("apple");

Steps:

  1. Compute hash

  2. Find bucket index

  3. Traverse bucket:

    • If LinkedList → iterate

    • If Tree → binary search

  4. Compare using:

key.equals(existingKey)

Important:
equals() is used to find the correct key — not ==.


Resizing (Rehashing)

Default initial capacity:

16

Default load factor:

0.75

Resize condition:

size > capacity × loadFactor

So:

16 × 0.75 = 12

When 13th element is added:
→ capacity doubles to 32
→ all elements are rehashed


Why hashCode() and equals() Matter

HashMap uses:

  1. hashCode() → to find bucket

  2. equals() → to find exact key inside bucket

If you override one,
you MUST override the other.

Otherwise, HashMap breaks.


Internal Node Structure (Simplified)

static class Node<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;
}

For tree buckets:

TreeNode extends Node

Time Complexity Summary

OperationAverageWorst Case
put()O(1)O(log n)
get()O(1)O(log n)
remove()O(1)O(log n)

Worst case happens when many collisions occur.


Not Thread Safe

HashMap is not synchronized.

For concurrency use:

  • ConcurrentHashMap

  • Collections.synchronizedMap()


Tip

If we ask “How does HashMap work?” we could say in this order:

  1. Array of buckets

  2. hashCode()

  3. Index calculation

  4. Collision handling

  5. Treeification (Java 8)

  6. Resize mechanism

  7. equals() importance


SQL index

In SQL, an index is a database object that provides a fast and efficient way to look up and retrieve data from a table. It is a data structure that improves the speed of data retrieval operations on a database table at the cost of additional storage space and update overhead during data modification.

Key Points about Indexes

1. Purpose
   - The primary purpose of an index is to enhance the speed of SELECT queries by reducing the number of rows that need to be scanned to satisfy a query condition.

2. Data Structure
   - An index is typically implemented as a B-tree or a hash data structure, allowing for efficient search, retrieval, and sorting of data.

3. Indexed Columns
   - Indexes are created on one or more columns of a table. These columns are known as indexed columns.

4. Types of Indexes
   - Single-Column Index: Created on a single column.
   - Composite Index: Created on multiple columns.
   - Unique Index: Ensures the uniqueness of values in the indexed columns.
   - Clustered Index: Defines the physical order of data in the table.
   - Non-Clustered Index: Does not affect the physical order of data in the table.

How Indexes Improve Query Performance

1. Faster Data Retrieval
   - Indexes allow the database engine to locate and retrieve specific rows quickly, especially when filtering or searching based on the indexed columns.

2. Avoiding Full Table Scans
   - Without indexes, the database engine may need to perform a full table scan to find the relevant rows. Indexes help avoid this by providing a more direct path to the required data.

3. Optimizing WHERE Clauses
   - Indexes significantly improve the performance of queries that include WHERE clauses, as they allow the database to skip irrelevant rows and focus on the ones that match the search condition.

4. Efficient Sorting and Grouping
   - Indexes enhance the performance of ORDER BY and GROUP BY operations, as the sorted or grouped data can be retrieved more efficiently using the index.

5. Enhancing Join Operations
   - When joining tables, indexes on the join columns can significantly speed up the process, reducing the need for nested loop joins or hash joins.

6. Covering Index
   - A covering index is an index that includes all the columns needed for a query, eliminating the need to access the actual table data. This can further enhance query performance.

Considerations and Best Practices

1. Balancing Act
   - While indexes improve read performance, they come with a cost in terms of storage space and potential overhead during write operations (inserts, updates, deletes). It's important to strike a balance based on the specific workload of the database.

2. Selective Indexing
   - Choose indexes based on the queries frequently executed in your application. Selective indexing on columns frequently used in WHERE clauses is generally beneficial.

3. Regular Maintenance
   - Indexes may need to be periodically rebuilt or reorganized to ensure optimal performance, especially in databases with high write activity.

4. Understand Query Execution Plans
   - Use tools and techniques to analyze query execution plans to understand how queries are utilizing indexes and where improvements can be made.

In summary, indexes in SQL play a crucial role in enhancing query performance by providing efficient access to data. Properly designed and maintained indexes can significantly improve the responsiveness of a database system, especially in scenarios with complex queries or large datasets.

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...