Java
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax
-
Section 3: Object-Oriented Java
-
Section 4: Collections Framework
-
Section 5: Exception Handling
-
Section 6: Generics
-
Section 7: Functional Java
-
Section 8: Concurrency
-
Section 9: I/O and NIO
-
Section 10: JVM Internals
-
Section 11: Modern Java Features
-
Section 12: Build Tools and Project Structure
-
Section 13: Testing
-
Section 14: Databases and Persistence
-
Section 15: Networking
-
Section 16: Design and Best Practices
-
Section 17: Reflection and Annotations
-
Section 18: Logging and Diagnostics
-
Section 19: Date, Time, and Internationalization
-
Section 20: Java Platform Module System
-
Section 21: Security in Java
-
Section 22: Advanced Collections and Data Structures
-
Section 23: More Concurrency Patterns
-
Section 24: Compression, Files, and System Integration
-
Section 25: GUI Programming
-
Section 26: Practical Projects
-
Section 27: Data Structures and Algorithms
-
Section 28: Interview and Algorithm Practice
-
Section 29: JSON and Data Interchange
-
Section 30: More Concurrency Utilities
-
Section 31: More Collections and Streams Practice
-
Section 32: More File and System Programming
-
Section 33: Standard Library Deep Dive
-
Section 34: More Practice and Drills
-
Section 35: More Testing and Quality
-
Section 36: More Design Patterns and Architecture
-
Section 37: Career and Ecosystem
-
Section 38: More OOP and Architecture Practice
-
Section 39: More Enterprise Concepts
-
Section 40: Advanced JavaFX
-
Section 41: More Interview Practice
46: HashMap, TreeMap, and LinkedHashMap
You've likely reached the point in your Java journey where you need to associate one piece of data with another—like a User ID mapped to a User object. At first glance, HashMap, TreeMap, and LinkedHashMap all look like they do the exact same thing: they implement the Map interface. Because of that, a lot of developers assume they are interchangeable and just pick one at random, or stick with HashMap for everything.
"But I put the items in this order!"
The most common misconception I see is the belief that a HashMap remembers the order in which you inserted your keys. It doesn't. Not even close. It uses a hashing function to distribute keys across buckets for maximum speed, and that process completely ignores your insertion sequence.
Map<String, Integer> inventory = new HashMap<>();
inventory.put("Iron Sword", 1);
inventory.put("Health Potion", 10);
inventory.put("Wooden Shield", 1);
inventory.put("Mana Elixir", 5);
// You might expect: Iron Sword, Health Potion, Wooden Shield, Mana Elixir
System.out.println(inventory);
// Actual output might be: {Mana Elixir=5, Iron Sword=1, Wooden Shield=1, Health Potion=10}
If you're building a UI where the order of items matters, using a HashMap will lead to a bug that's frustratingly intermittent—sometimes the order looks right by coincidence, and other times it's a complete jumble. I've spent way too many hours debugging "random" UI jumps because someone used a HashMap where they needed stability.
Picking the Right Tool for the Job
The real difference between these three isn't what they store, but how they organize that storage. Depending on your needs, you'll choose one of these three strategies.
- HashMap: This is your "go-to" for raw performance. It offers O(1) time complexity for basic operations. If you don't care about the order of your keys and just want the fastest possible lookup, use this.
- LinkedHashMap: Think of this as a
HashMapwith a double-linked list running through it. It maintains insertion order. If you put "Sword" then "Shield", they will stay in that order when you iterate over the map. It's slightly slower and uses more memory than aHashMap, but it's a lifesaver for caches or history lists. - TreeMap: This one doesn't care when you inserted the item; it cares about the natural order of the keys (or a custom
Comparatoryou provide). It stores keys in a red-black tree, meaning your keys are always sorted. This is O(log n) performance—slower than the others, but it allows you to do things like "give me all keys between 'A' and 'F'".
Here is how they look side-by-side using the same data:
Map<String, Integer> hash = new HashMap<>();
Map<String, Integer> linked = new LinkedHashMap<>();
Map<String, Integer> tree = new TreeMap<>();
String[] items = {"Zebra", "Apple", "Mango"};
for(String s : items) {
hash.put(s, 1);
linked.put(s, 1);
tree.put(s, 1);
}
System.out.println("HashMap: " + hash); // Unpredictable order
System.out.println("LinkedHashMap: " + linked); // [Zebra, Apple, Mango]
System.out.println("TreeMap: " + tree); // [Apple, Mango, Zebra]
My rule of thumb? Default to HashMap. If you realize you need to iterate in the order you added things, switch to LinkedHashMap. If you need the keys to be sorted alphabetically or numerically, go with TreeMap.
📋 Practical Task
Build a Sorted Player Inventory System
You are building a gear management system for an RPG. The game requires two different views of the player's inventory:
- The "Recent Items" View: A list of items shown in the exact order they were picked up.
- The "Alphabetical Archive" View: A list of all items sorted by their name.
Your Task:
- Create a class called
InventoryManager. - Implement a method
addItem(String itemName, int quantity)that adds the item to both aLinkedHashMapand aTreeMap. - Implement a method
printRecentItems()that prints the contents of theLinkedHashMap. - Implement a method
printAlphabeticalItems()that prints the contents of theTreeMap. - In your
mainmethod, add the following items in this specific order:"Healing Herb","Ancient Map","Steel Plate", and"Bronze Key". - Call both print methods and verify that the "Recent" view maintains the insertion order while the "Alphabetical" view is sorted A-Z.
There are no comments for now.