🚀 Day 44 of #100DaysOfCode — Mastering HashSet Internals in Java Today I went deep into one of the most commonly used collections in Java — HashSet 🔥 Not just usage… but how it actually works internally. 🧠 What is HashSet? 👉 HashSet is backed by a HashMap 👉 Stores elements as keys with a dummy value ⚙️ How HashSet Adds an Element? add(element) ↓ hashCode() → object-specific logic ↓ hash = h ^ (h >>> 16) // bit spreading ↓ index = (n - 1) & hash // bucket index ↓ bucket check ↓ if empty → insert if collision: ↓ equals() check ↓ if duplicate → reject ❌ else: ↓ add to LinkedList ↓ if bucket size ≥ 8 and capacity ≥ 64 → convert to Tree ↓ if bucket size ≤ 6 → convert back to LinkedList 🔍 Key Concepts I Learned 🔹 1. hashCode() Converts object → integer Used to decide bucket location 🔹 2. equals() Used to check duplicate Same hashCode ≠ same object 🔹 3. Collision Handling Multiple elements in same bucket Stored as: LinkedList (< 8 elements) Red-Black Tree (≥ 8 elements) 🌳 Tree Conversion Rules Bucket size ≥ 8 → Tree Bucket size ≤ 6 → Back to LinkedList Capacity must be ≥ 64 for tree conversion 🔄 Rehashing (Very Important) Default capacity = 16 Load factor = 0.75 👉 Threshold = 16 × 0.75 = 12 When size exceeds 12: Capacity doubles → 32 All elements are rehashed New bucket positions are recalculated ⚡ Why HashSet is Fast? Average Time Complexity: O(1) Due to: Efficient hashing Bitwise index calculation Tree optimization for collisions 🧠 Final Takeaway 👉 hashCode decides bucket 👉 equals decides duplicate 👉 structure (List/Tree) depends on size This deep dive really helped me understand why overriding hashCode() and equals() is critical in real-world applications. 🙏 Special thanks to my mentor Suresh Bishnoi sir for guiding me through these concepts and helping me understand the internals so clearly! #Java #HashSet #DataStructures #BackendDevelopment #CodingJourney #100DaysOfCode #LearnInPublic
Mastering HashSet Internals in Java with Suresh Bishnoi
More Relevant Posts
-
📘 Day 25 – Unlocking the Magic of Java Casting Today I dove deep into non-primitive type casting in Java and had that haha moment! 💡 ✨ Upcasting – Treating a subclass object as a superclass reference. It makes my code cleaner, flexible, and ready for change. ⚡ Downcasting – Converting back safely to a subclass. Done wrong, it throws ClassCastException, but done right, it’s pure power. 🛡 instanceof operator – My safety net! It checks object type before casting, keeping runtime errors away. Seeing objects flow up and down the hierarchy revealed the true beauty of polymorphism, code that’s adaptable, maintainable, and future-proof. 💬 What really clicked: Java isn’t just about syntax; it’s about managing relationships between objects smartly. This makes every line of code safer, cleaner, and smarter. #Java #OOP #Polymorphism #Upcasting #Downcasting #ClassCastException #InstanceOf #DailyLearning #CodeBetter #ProgrammingJourney #DevLife
To view or add a comment, sign in
-
Day 73 of #90DaysDSAChallenge Solved LeetCode 451: Sort Characters By Frequency Learned an important Java design concept today. Problem Overview: The task was to sort characters in a string based on descending frequency. What confused me initially: Why create a separate Freq class instead of just using HashMap and PriorityQueue directly? Key Learning: PriorityQueue stores one complete object at a time. For this problem, each item needs two pieces of data together: Character Frequency Example: Instead of storing: e and 2 separately We package them as: Freq('e', 2) That custom class acts like a container holding both values in one object, so PriorityQueue can compare and sort them correctly. Why this matters: This taught me that custom classes in Java are often not about complexity, they simply bundle related data into one manageable unit. Alternative approach: We can also use Map.Entry<Character, Integer> instead of creating a custom class, but building Freq makes the logic easier to understand while learning. Today’s takeaway: Not every class is for business logic — sometimes it exists just to package data cleanly. #Java #90DaysDSAChallenge #LeetCode #PriorityQueue #HashMap #CodingJourney #ProblemSolving
To view or add a comment, sign in
-
-
Solved Sort Characters By Frequency -> LeetCode Medium, String + HashMap in Java. What I built: Count frequency of each character using HashMap, convert it to a list, sort by frequency in decreasing order, then build the result using StringBuilder. Problem I faced: First I tried storing frequencies in an array and sorting it , but that was O(n log n). Switched to HashMap for frequency counting which brings sorting down to O(k log k) where k is number of unique keys. Since max ASCII characters are 128, it's basically O(1). The part I got stuck on -> I didn't know how to sort a HashMap. Googled it, found out HashMap can't be sorted directly. So converted it to a List of entries and sorted that using a lambda comparator. Took help for two things only — how to sort a HashMap, and the syntax for the comparator. Logic was mine. Still learning HashMap operations properly, but slowly getting comfortable . Open to better approaches! Github: https://lnkd.in/gBgb3jAK #DSA #Java #LeetCode #HashMap #Strings #LearningInPublic
To view or add a comment, sign in
-
🚀 Day 34 of Java Deep Dive: Mastering Sets & Maps! I just finished a comprehensive deep dive into the Java Collections Framework, specifically focusing on the internal workings and specialized implementations of Sets and Maps. Understanding these data structures is the key to writing efficient, production-grade Java code. Here’s a breakdown of what I covered: • Set Hierarchy & Internal Methods: Explored how Set inherits its power from the Collection and Iterable interfaces. Interestingly, Set doesn't define many unique methods—it leverages the robust ones already in Collection like add(), remove(), and contains() • TreeSet Under the Hood: It’s not just a simple interface. TreeSet actually implements NavigableSet and SortedSet, providing advanced navigation features like finding the closest matches or sub-sets • The Power of Maps: Went beyond the standard HashMap to explore: • EnumMap: Highly optimized for when keys are Enums • IdentityHashMap: A unique case that uses == (reference equality) instead of .equals() • ConcurrentHashMap: The modern go-to for thread-safe operations, offering better performance than the legacy Hashtable by avoiding full map locking • Optimization Secrets: Learned how Java internally optimizes HashMap to handle collisions and maintain high performance • Topic - Key Insight Set Interface - Inherits all core functionality from the Collection interface. TreeSet Hierarchy - Implements NavigableSet and SortedSet for ordering. Internal Storage - Sets internally use a HashMap (default bucket size of 16). ConcurrentHashMap - Preferred over Hashtable for multi-threaded environments. Specialized Maps - Covered EnumMap, IdentityHashMap, and WeakHashMap. Feeling much more confident in choosing the right tool for the right job in Java! Huge thanks to Aditya Tandon and Rohit Negi from CoderArmy for the incredible depth in this series. #Java #SoftwareEngineering #JavaCollections #CodingJourney #BackendDevelopment #CoderArmy
To view or add a comment, sign in
-
-
I always thought Class.forName("com.example.MyClass") just "loads a class." Turns out I had no idea what was actually happening. Went down a rabbit hole this week into how Java reflection works under the hood. Here is what I found: When the JVM loads a class, it creates two separate things: An InstanceKlass, a C++ struct in Metaspace. This is the JVM's actual representation of your class. Method table, field table, bytecode, runtime constant pool, all of it lives here. The execution engine works directly off this. A Class<?> object on the heap. This is what your Java code sees. It just holds a pointer back to the InstanceKlass. So every time you call getDeclaredMethods() or getField(), Java is doing this: Class<?> on heap -> klass pointer -> InstanceKlass in Metaspace That boundary crossing, plus access checks, is exactly why reflection has overhead. One more thing that surprised me: the String intern pool is not in Metaspace. It is a native C++ hash table called StringTable inside HotSpot, lives on the heap, uses weak references so unused strings get collected. Completely global across the JVM process. Most Java developers never look at this layer. Once you do, a lot of things that felt like magic start making sense. Going to keep writing about JVM internals. What part of the JVM caught you off guard when you first looked deeper? #Java #JVM #BackendDevelopment #JavaInternals #SpringBoot
To view or add a comment, sign in
-
Most Java devs know Collections exist. Few know which one to actually pick. 🧵 After years of backend work, I still see the same mistakes in code reviews: LinkedList used where ArrayList is 3x faster HashMap in multi-threaded code with no sync Custom objects in HashSet without equals() + hashCode() So I built this visual cheat sheet. 9 slides. Every collection. Real trade-offs. Here's what's inside 👇 📌 Full hierarchy from Iterable down to every implementation 📌 ArrayList vs LinkedList =>when each actually wins 📌 HashSet / LinkedHashSet / TreeSet => ordering guarantees explained 📌 HashMap vs TreeMap vs LinkedHashMap =>feature table 📌 Queue & Deque => why ArrayDeque beats Stack and LinkedList 📌 Big-O cheat sheet => all 10 collections in one table 📌 Top 5 interview questions => with answers that impress 🚀 My Daily Java Collections Decision Rule Confused which collection to use? This quick guide helps me every day 👇 👉 Need fast random access? → ArrayList ⚡ 👉 Need unique elements + fast lookup? → HashSet 🔍 👉 Need key-value pairs (default choice)? → HashMap 🗂️ 👉 Need sorted data? → TreeMap / TreeSet 🌳 👉 Need Stack / Queue operations? → ArrayDeque 🔄 👉 Need priority-based processing? → PriorityQueue 🏆 ♻️ Repost if this helps a Java dev on your feed. #Java #JavaDeveloper #Collections #DataStructures #Backend #BackToBasics #SpringBoot #CodingInterview #SoftwareEngineering #Programming
To view or add a comment, sign in
-
🚀 Day 53 – Mastering ArrayDeque in Java Today I explored one of the most efficient data structures in Java Collections – ArrayDeque 🔥 📌 Key Learnings: 🔹 ArrayDeque is a resizable array-based Deque (Double Ended Queue) 🔹 Supports insertion & deletion from both ends (front & rear) 🔹 No indexing → cannot use get/set methods 🔹 No null values allowed (throws runtime exception) 🔹 Duplicates & heterogeneous data allowed 🔹 Faster than LinkedList due to no memory overhead ⚙️ Traversal Techniques: ✔ For-each loop ✔ Iterator ✔ Descending Iterator (reverse traversal) 💡 Why ArrayDeque? 👉 O(1) performance for add/remove operations 👉 Best choice for implementing: Stack (LIFO) Queue (FIFO) Deque 🧠 Big Takeaway: ArrayDeque = Fast + Memory Efficient + Flexible (Stack/Queue/Deque in one) Consistency is the key 🔑 — learning something new every day! #Java #DataStructures #ArrayDeque #JavaCollections #CodingJourney #100DaysOfCode #LearningDaily
To view or add a comment, sign in
-
-
🚀 Mastering Java Through LeetCode 🧠 Day 32 Today I solved an Easy-level Tree problem that strengthened my understanding of Recursion + Depth Calculation — a fundamental concept for tree-based problems 📌 LeetCode Problem Solved: Q.104. Maximum Depth of Binary Tree 💭 Problem Summary: Given a binary tree, the task is to find the maximum depth — i.e., the number of nodes along the longest path from root to leaf. 🧠 Approach (Optimal): Instead of iterating level by level, I used a clean recursive approach: ✔️ If node is null → return 0 ✔️ Recursively calculate left subtree depth ✔️ Recursively calculate right subtree depth ✔️ Return 1 + max(left, right) ⚡ Key Learning: Recursion makes tree problems much simpler when you think in terms of “what should each function return for a node?” Complexity: Time: O(n) Space: O(h) Takeaway: Tree problems become easier once you master recursion and start recognizing patterns. Consistency is the key — showing up every day #Day32 #LeetCode #Java #DSA #CodingJourney #Recursion #BinaryTree #100DaysOfCode #SoftwareEngineering
To view or add a comment, sign in
-
-
Day 94/100: #LeetCodeChallenge – Grid Partitioning in Java 🧩💻 Another day, another algorithmic deep dive! Today’s problem was about determining whether a grid can be partitioned in a specific way. While the problem may seem straightforward at first, the real challenge lies in handling edge cases, optimizing for efficiency, and ensuring clean, maintainable code. 🔍 Key takeaways from today’s solution: Understanding 2D array traversal and prefix sums Handling edge cases like 1x1 grids early Writing readable code that can scale with larger test cases Even though the sample output shows "You must run your code first," the process of thinking through the logic, testing edge cases, and refining the approach is where the real growth happens. Every problem adds another tool to the problem-solving toolkit. 🚀 Consistency > Intensity. Day 94 is in the books. On to the final sprint! #100DaysOfCode #LeetCode #Java #CodingChallenge #ProblemSolving#GridPartitioning #DataStructuresAndAlgorithms #TechJourney#SoftwareEngineering #CodeNewbie #DeveloperLife #AlgorithmDesign#ConsistencyIsKey
To view or add a comment, sign in
-
-
🚀 Day 54 – Mastering TreeSet in Java Today I explored one of the most powerful classes in the Java Collection Framework — TreeSet. 🔍 Key Learnings: ✅ Stores unique elements (no duplicates) ✅ Maintains automatic sorting (ascending order) ✅ Uses Binary Search Tree (BST) internally ✅ Sorting is achieved using Inorder Traversal (LVR) ✅ Does not allow null values ✅ Does not support heterogeneous data (requires comparison) 📌 Important Concepts: Left < Root < Right (BST logic) No indexing → cannot use traditional for loop Access using Iterator / For-Each Supports both ascending & descending traversal 🛠️ Methods I Practiced: first() & last() headSet(), tailSet(), subSet() ceiling(), floor(), higher(), lower() pollFirst(), pollLast() 💡 Real-world Use Case: Useful for building features like leaderboards, ranking systems, and sorted data processing. 📈 Understanding how TreeSet works internally (BST + traversal) really helped me connect Data Structures with Java Collections. #Java #CollectionsFramework #TreeSet #DataStructures #LearningJourney #100DaysOfCode #JavaDeveloper
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development