💡 What I Learned Today: equals() and hashCode() in Java Today I explored how equals() and hashCode() work together — a small concept that plays a huge role in collections like HashMap and HashSet. Here’s what I learned 👇 🔹 equals() → compares two objects for logical equality. 🔹 hashCode() → returns an integer (hash value) used by hash-based collections. ✅ Key rule: If two objects are equal according to equals(), they must have the same hash code. Otherwise, collections like HashMap or HashSet may not work correctly. Example: - If you override equals() in your class but forget to override hashCode(), you might end up with duplicate entries in a HashSet or missing keys in a HashMap. Understanding this relationship ensures your objects behave correctly in all Java collections — a simple but powerful concept! #Java #HashCode #Equals #Collections #JavaDeveloper #CodingTips #LearningJourney
Java equals() and hashCode() for collections
More Relevant Posts
-
💡 HashMap vs HashSet — Same Roots, Different Purpose Ever wondered how HashMap and HashSet work internally in Java? Here’s the quick breakdown 👇 🔹 HashMap Stores data in key–value pairs. Uses hashing to compute an index in an internal array (called a bucket). If two keys produce the same hash, Java handles it using LinkedList or Balanced Tree (from Java 8) to avoid performance loss. Average lookup: O(1) ⚡ 🔹 HashSet Internally backed by a HashMap! It stores elements as keys in the map, with a dummy constant object as the value. Ensures no duplicates because keys in a HashMap are unique. 🔹 Core concept: Hashing + equals() + hashCode() = Fast lookups with uniqueness guarantee. 🧠 Mastering this helps in writing optimized code and debugging performance issues effectively. #Java #HashMap #HashSet #DataStructures #Coding #BackendDevelopment #Performance #SoftwareEngineering
To view or add a comment, sign in
-
🎯 Day 62 of #100DaysOfLeetCode Today I solved the “Merge Two Sorted Lists” problem using Java This problem is a great exercise in understanding how to work with Linked Lists and pointer manipulation. The goal is to merge two sorted linked lists into one sorted list — without using extra space for another list. Key Concepts Practiced: Linked List traversal Dummy node technique Efficient merging using pointers Handling null edge cases Approach Summary: Create a dummy node to simplify edge cases. Use two pointers to traverse both lists. Compare values and link nodes in sorted order. Attach any remaining nodes at the end. #100DaysOfCode #LeetCode #Java #CodingChallenge #DataStructures #LinkedList #ProblemSolving #SoftwareEngineering
To view or add a comment, sign in
-
-
📌 Today's Focus: Static & Non-Static Blocks in Java ⚙️ STATIC BLOCK:- 👉 Changed "Once upon class-loading. Shared Destiny!" to: 👉Executed first, only ONCE." 👉Initializes static variables and resources 👉Added a label pointing to the block: "Class Loader" NON-STATIC BLOCK:- 👉Changed Each new friend (object) own private story! to: 👉Executed every time. NEW objects created 👉Initializes instance variables 👉Added a label pointing to the non-static blocks: "Object Initialization" (to link it directly to object creation). #Java #StaticBlock #NonStaticBlock #JavaBasics #OOP #JVM #DailyJava #DeveloperJourney #CodeEveryday Thank you Anand Kumar Buddarapu for explaing very clearly.
To view or add a comment, sign in
-
-
Day 80 of #100DaysOfCode Solved Frequency Sort in Java 🔠 Approach Today's problem was to sort an array based on the frequency of its numbers. My initial solution was accepted, but it exposed a major efficiency gap! My strategy involved: Sorting the array first. Using nested loops to count the frequency of each number and store it in a HashMap. (Implied) Using the counts to perform the final custom sort. The core issue was the counting method: running a full loop inside another full loop to get the frequency. This quadratic $O(N^2)$ counting completely tanked the performance. ✅ Runtime: 29 ms (Beats 12.02%) ✅ Memory: 45.26 MB (Beats 5.86%) Another great lesson in algorithmic complexity! The difference between $O(N^2)$ and the optimal $O(N \log N)$ for this problem is massive. Time to refactor and implement the fast, single-pass $O(N)$ frequency count using getOrDefault! 💪 #Java #100DaysOfCode #LeetCode #CodingChallenge #Algorithms #Arrays #HashMap #Optimization #ProblemSolving
To view or add a comment, sign in
-
-
🚀Day 88 – DSA in Java Solved “Hand of Straights” (LeetCode – Medium) Approach: ➡️ Sorted the array ➡️ Used HashMap to track frequencies ➡️ Formed consecutive groups of size k ➡️ Decremented counts as groups formed ⚡ Runtime: 24 ms (Beats 89.95%) 💾 Memory: 45.2 MB (Beats 89.4%) Explored how HashMap + sorting can simplify grouping problems and also learned about TreeMap for maintaining sorted order dynamically. #Day88 #LeetCode #Java #DSA #ProblemSolving #LearningEveryday
To view or add a comment, sign in
-
-
🚀 Ever wondered how HashSet avoids duplicate elements in Java? When I first learned about HashSet, it seemed magical — how can a data structure automatically reject duplicates? But once I explored its internals, it got really interesting 👇 🧩 Here’s what happens under the hood: When we call set.add(element), the HashSet internally uses a HashMap. 1️⃣ It calculates the hashCode() of the element to find the correct bucket. 2️⃣ Then it checks if any existing key in that bucket has the same hashCode() and is equal according to equals(). 3️⃣ If not found → the element is added. 4️⃣ If found → it’s simply ignored (that’s how duplicates are prevented!). What’s more: LinkedHashSet uses a LinkedHashMap internally → preserves insertion order. TreeSet uses a TreeMap → keeps elements sorted. ✨ Key takeaway: Every collection in Java hides a smart internal design — once you understand it, you start writing code with a whole new perspective. #Java #HashSet #DataStructures #CodingInsights #DeveloperJourney
To view or add a comment, sign in
-
📌 Today's Focus: Static & Non-Static Blocks in Java ⚙️ Here’s what I explored today 👇 🧠 Understanding Blocks in Java: 🔹 Static Block: Runs only once when the class is loaded into memory. 🔹 Non-Static (Instance) Block: Runs every time an object is created. 🔍 Code Flow (From My Notes): 1️⃣ When the program starts → static block executes automatically. 2️⃣ Each time new StaticDemo() is created → non-static block executes. 3️⃣ Static blocks are ideal for initialization tasks (like setting up config or loading resources). 🧩 Execution Order Example: Class loads → static block called Object 1 created → non-static block called Object 2 created → non-static block called 🎯 Key Learning: Static blocks execute once per class, Non-static blocks execute once per object. #Java #StaticBlock #NonStaticBlock #JavaBasics #OOP #JVM #DailyJava #DeveloperJourney #CodeEveryday Anand Kumar Buddarapu
To view or add a comment, sign in
-
🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA
To view or add a comment, sign in
-
-
🚀 Day 55 of #100DaysOfCode Challenge Problem: LeetCode #219 – Contains Duplicate II Language: Java ☕ Today I solved an interesting array problem that checks whether a duplicate element exists within a given distance k in the array. 💡 Logic: Use a HashMap to remember the last index of each number. If the same number appears again, check if the difference between indices ≤ k. If yes → return true, else keep checking. 💻 Code: import java.util.HashMap; public class Solution { public boolean containsNearbyDuplicate(int[] nums, int k) { HashMap<Integer, Integer> map = new HashMap<>(); for (int i = 0; i < nums.length; i++) { if (map.containsKey(nums[i]) && i - map.get(nums[i]) <= k) { return true; } map.put(nums[i], i); } return false; } } 🧠 Example: Input: [1,2,3,1], k = 3 Output: true ✅ (same number 1 appears within distance 3) ⚙️ Key Concepts: HashMap for quick lookup Difference check using indices Time Complexity → O(n) Space Complexity → O(n) 💬 Every day’s problem teaches me something new — today it was about using maps smartly to track elements efficiently. On to the next challenge! 💪 #Day55 #LeetCode #Java #100DaysOfCode #CodingJourney #ProblemSolving #HashMap #DSA
To view or add a comment, sign in
-
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