Java.Collections.Is it possible for HashMap to degenerate into a list even with keys having different hashCode()?

Yes, a HashMap can degenerate into a linked list even if the keys have different hashCode() values, under certain conditions. Let me explain how and why.

🔍 How HashMap organizes entries:

  1. Each key’s hashCode() is used to determine its bucket index via this internal hash function:

Even if two keys have different hashCode() values, their hashed indices may still collide if:

  • They map to the same bucket index due to modulo with the table size.
  • The internal hash function doesn’t spread them out well enough.
int tableSize = 16;
int hash1 = 0b00010000; // 16
int hash2 = 0b00110000; // 48
// Both (hash & (tableSize - 1)) = 0

➡️ Both keys, despite different hashCode()s, can end up in the same bucket.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.Is it possible for HashMap to degenerate into a list even with keys having different hashCode()?

Java.Collections.What is the estimated time complexity of operations on elements from HashMap? Does HashMap guarantee the specified complexity of element selection?

✅ Estimated Time Complexity of HashMap operations

OperationAverage CaseWorst Case (pre-Java 8)Worst Case (Java 8+)
get(key)O(1)O(n)O(log n) (with tree bins)
put(key, value)O(1)O(n)O(log n)
remove(key)O(1)O(n)O(log n)
containsKey()O(1)O(n)O(log n)

🧠 Why the difference?

  • In a perfect hash scenario, keys are evenly distributed across buckets → each bucket has few elements → O(1) time.
  • In the worst case, all keys hash to the same bucket:
    • Before Java 8, collisions were handled via linked lists → O(n) traversal in a bucket.
    • Since Java 8, if a bucket becomes too dense (≥ 8 entries), it is converted into a balanced tree (a red-black tree), so lookup time becomes O(log n).
Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.What is the estimated time complexity of operations on elements from HashMap? Does HashMap guarantee the specified complexity of element selection?

Java.Collections.What is the initial number of buckets in HashMap?

In Java, the initial number of buckets in a HashMap depends on the constructor used when creating the map.

By default:

Map<K, V> map = new HashMap<>();

👉 The initial capacity is 16 buckets.

Key details:

  • Initial Capacity: 16 (this means 16 buckets internally).
  • Load Factor: 0.75 (this means the map resizes when 75% of the capacity is filled, i.e., 12 entries in this case).
  • Buckets: These are actually positions in an internal array (Node[] table) where hash collisions are resolved using linked lists or balanced trees (since Java 8).

You can also specify a custom capacity:

Map<K, V> map = new HashMap<>(32); // 32 buckets initially
Posted in Без рубрики | Comments Off on Java.Collections.What is the initial number of buckets in HashMap?

Java.Collections.How does HashMap work when trying to store two elements in it by keys with the same hashCode(), but for which equals() == false?

🎯 TL;DR:

✅ HashMap can store multiple keys with the same hashCode() as long as equals() returns false — because it uses both hashCode() and equals() to handle collisions properly.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.How does HashMap work when trying to store two elements in it by keys with the same hashCode(), but for which equals() == false?

Java.Collections.According to Knuth and Cormen, there are two main implementations of a hash table: open addressing and chaining. How is HashMap implemented? Why do you think this implementation was chosen? What are the pros and cons of each approach?

🧠 Hash Table Implementations (per Knuth & CLRS)

1. Chaining

Each bucket contains a list (or tree) of entries. Collisions are handled by appending to that list.

2. Open Addressing

All entries live in the array itself. On collision, we probe (linear, quadratic, or double hashing) to find the next free slot.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.According to Knuth and Cormen, there are two main implementations of a hash table: open addressing and chaining. How is HashMap implemented? Why do you think this implementation was chosen? What are the pros and cons of each approach?

Java.Collections.How is HashMap constructed?

🔧 How is a HashMap constructed?

🔹 At a high level, a HashMap is:

A hash table implementation that maps keys to values using a combination of array + linked list + (sometimes) red-black trees.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.How is HashMap constructed?

Java.Collections.How does SortedMap “sort” itself, other than the fact that toString() outputs all elements in order?

✅ Yes — SortedMap is an interface in Java.

It is part of the Java Collections Framework, and it defines the contract for a map that maintains sorted order of keys.

public interface SortedMap<K, V> extends Map<K, V> {
    Comparator<? super K> comparator();
    SortedMap<K, V> subMap(K fromKey, K toKey);
    SortedMap<K, V> headMap(K toKey);
    SortedMap<K, V> tailMap(K fromKey);
    K firstKey();
    K lastKey();
}
Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.How does SortedMap “sort” itself, other than the fact that toString() outputs all elements in order?

Java.Collections.LinkedHashMap – what is from LinkedList and what is from HashMap?

🔍 What is LinkedHashMap?

LinkedHashMap is a hash table + doubly linked list implementation of the Map interface.
It maintains the insertion order (or access order) of entries, unlike regular HashMap.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.LinkedHashMap – what is from LinkedList and what is from HashMap?

Java.Collections.What is WeakHashMap?

🧩 What is a WeakHashMap?

A WeakHashMap is a hash table-based map where the keys are stored as weak references.

If a key is no longer referenced elsewhere in your application, then the entry will be automatically removed by the garbage collector — poof 💨

It’s like a self-cleaning map that helps you avoid memory leaks when you’re associating data with objects you don’t “own”.

Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.What is WeakHashMap?

Java.Collections.WeakHashMap uses WeakReferences. Why not create a PhantomHashMap on PhantomReferences?

🔍 Quick Refresher

Reference Typeget() returns?Enqueued when?Common Use Case
WeakReference✅ the objectWhen object is weakly reachableWeakHashMap, caches
PhantomReference❌ always nullAfter finalization, before GC reclaimsCleanup, monitoring, resource release
Continue reading →
Posted in Без рубрики | Comments Off on Java.Collections.WeakHashMap uses WeakReferences. Why not create a PhantomHashMap on PhantomReferences?