惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
Y
Y Combinator Blog
博客园_首页
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
B
Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
WordPress大学
WordPress大学
L
LangChain Blog
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Java Questions on Collections
Tapas Pal · 2026-05-12 · via DEV Community

Tapas Pal

Day-1
1. How does HashMap work internally?
Answer:
High-Level Internal Structure
Internally, HashMap uses:
Array + LinkedList + Red-Black Tree (Java 8+)

Internal Data Structure

transient Node<K,V>[] table;

Enter fullscreen mode Exit fullscreen mode

This is an array of buckets.
Each bucket stores:
single node
linked list
tree nodes

Basic Working Flow
When you do:

map.put(key, value);

Enter fullscreen mode Exit fullscreen mode

HashMap performs:

  1. Calculate hashCode()
  2. Calculate bucket index
  3. Store value in bucket
  4. Handle collision if needed

Step-by-Step Example

Map<Integer, String> map = new HashMap<>();
map.put(101, "John");
map.put(102, "David");
map.put(103, "Alex");

Enter fullscreen mode Exit fullscreen mode

Now let us understand internally what happens.
Step 1: Create HashMap

Map<Integer, String> map = new HashMap<>();

Enter fullscreen mode Exit fullscreen mode

Internally:
capacity = 16
loadFactor = 0.75
threshold = 12

Meaning:
resize after 12 elements
Internal Array

Initially: table[16]
Like:
index
0
1
2
...
15

All buckets empty initially.
Step 2: Insert First Entry

map.put(101, "John");

Enter fullscreen mode Exit fullscreen mode

Internal Working
A. Calculate hashCode()
For Integer:

hash = key.hashCode()

Enter fullscreen mode Exit fullscreen mode

For 101: hash = 101
B. Calculate Bucket Index
Formula:

index = (n - 1) & hash

Enter fullscreen mode Exit fullscreen mode

Where: n = capacity = 16
So: 15 & 101
Binary:
15 = 00001111
101 = 01100101

Result: 5
So element stored in: bucket 5

Internal Structure

table[5] → Node(101, "John")

Enter fullscreen mode Exit fullscreen mode

Step 3: Insert Another Entry
map.put(102, "David");
Hash: 102
Index: 15 & 102 = 6
Stored at: bucket 6

Current Structure
table[5] → (101, John)
table[6] → (102, David)

What is a Node Internally?
Simplified internal class:

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

Enter fullscreen mode Exit fullscreen mode

Collision Handling
Now suppose:

map.put(117, "Mike");

Enter fullscreen mode Exit fullscreen mode

Why Collision Happens?
Index formula: 15 & 117 = 5
Same bucket as 101.

Now What Happens?
HashMap creates linked list.
table[5]

(101, John)

(117, Mike)

This is collision handling.
How Retrieval Works
Suppose:

map.get(117);

Enter fullscreen mode Exit fullscreen mode

Step-by-Step Retrieval

Step 1: Calculate hash
hash = 117
Step 2: Find bucket
15 & 117 = 5

Go to bucket 5.
Step 3: Traverse nodes
Bucket contains:

(101, John)
(117, Mike)

Enter fullscreen mode Exit fullscreen mode

HashMap checks: equals()
until matching key found.
Returns: Mike
Why equals() is Important?
Hash collision possible.
So HashMap uses:
`1. hashCode()

  1. equals()`

Both are mandatory.
Internal Put Logic (Simplified)

public V put(K key, V value) {
    int hash = hash(key);
    int index = (table.length - 1) & hash;
    Node<K,V> node = table[index];
    if(node == null) {
        table[index] = new Node<>(hash, key, value);
    } else {
        // collision handling
        // traverse linked list
        // compare using equals()
        // update or append
    }
}

Enter fullscreen mode Exit fullscreen mode

Java 8 Optimization

Before Java 8:
collisions stored as linked list only
Problem: worst-case O(n)

Java 8 Improvement
If bucket size becomes: > 8
Linked list converts to: Red-Black Tree
called: Treeification
Now complexity becomes: O(log n)
instead of: O(n)
Visual Example
Before Treeify
Bucket 5:
A → B → C → D → E → F → G → H → I
Search slow.

After Treeify
          D
        /   \
       B     G
      / \   / \
     A  C  F  I

Enter fullscreen mode Exit fullscreen mode

Faster searching.
Important Interview Point
Why Capacity Always Power of 2?
Because index calculation:

(n - 1) & hash

Enter fullscreen mode Exit fullscreen mode

is faster than modulo:

hash % n

Enter fullscreen mode Exit fullscreen mode

Load Factor Default: 0.75

Meaning: resize when 75% full

Rehashing
When threshold exceeded:

  1. New bigger array created
  2. Entries redistributed Example: 16 → 32

*Why Immutable Keys Recommended?
*

Suppose:

class Employee {

    String name;
}

Enter fullscreen mode Exit fullscreen mode

If name changes:

  • hashCode changes
  • retrieval fails

Very dangerous.
That is why:

  • String
  • Integer
  • immutable objects

recommended as keys.

**Real Interview Example
**Bad Mutable Key

class Employee {
    String name;
    Employee(String name) {
        this.name = name;
    }
    @Override
    public int hashCode() {
        return name.hashCode();
    }
    @Override
    public boolean equals(Object obj) {
        Employee e = (Employee) obj;
        return this.name.equals(e.name);
    }
}

Enter fullscreen mode Exit fullscreen mode

Problem

Employee e = new Employee("John");
map.put(e, "Developer");
e.name = "David";
map.get(e); // FAILS

Enter fullscreen mode Exit fullscreen mode

Because:

  • bucket changed
  • object unreachable

Time Complexity
Operation Average Worst
put O(1) O(n)
get O(1) O(n)
remove O(1) O(n)

Java 8 treeification improves worst case:

O(log n)

Enter fullscreen mode Exit fullscreen mode

Internal Hash Function
Java improves hash distribution:

static final int hash(Object key) {
    int h;
    return (key == null)
            ? 0
            : (h = key.hashCode()) ^ (h >>> 16);
}

Enter fullscreen mode Exit fullscreen mode

This avoids poor bucket distribution.
*Null Handling *
HashMap allows:

  • one null key
  • multiple null values

Null key always stored in: bucket 0
Important Differences
Feature HashMap Hashtable
Thread-safe No Yes
Null allowed Yes No
Performance Faster Slower