Câu hỏi phỏng vấn Java
Câu hỏi

How HashMap works in Java?

Câu trả lời

A HashMap in Java is a part of the Java Collections Framework and is used to store data in key-value pairs. It implements the Map interface and is based on the hash table data structure. Here's a detailed explanation of how HashMap works in Java:

Key Components of HashMap

  1. Storage:

    • HashMap stores its data in an array of nodes, where each node is an instance of a class that contains four fields: key, value, hash (the hash code of the key), and next (a reference to the next node in the chain).
  2. Hash Function:

    • The hash function is used to compute an index in the array for storing the key-value pair. This function uses the hashCode() method of the key object, which is then transformed to reduce the risk of collisions.

Process of Storing Data

  1. Key-Value Pair Insertion (put method):
    • When the put(K key, V value) method is called, HashMap calculates the hash code of the key.
    • Using this hash code, it determines the bucket location (index in the array) where this key-value pair should be stored.
    • If there are no existing entries in the calculated bucket, the key-value pair is stored there.
    • If a collision occurs (i.e., two different keys have the same hash code or array index), the new entry is added to a linked list at that index. The new entry becomes the head of the list, and its next field points to the previous head.

Retrieval of Data

  1. Value Retrieval (get method):
    • To retrieve a value, the get(Object key) method calculates the hash code of the key to find the bucket location.
    • If the bucket contains only one entry, it checks the key using the equals() method and returns the value if it matches.
    • If the bucket contains multiple entries (linked list), it traverses the list and uses the equals() method to find the correct node corresponding to the key, and returns its value.

Handling Collisions

  • Chaining: As mentioned, HashMap handles collisions using a linked list at each bucket. Each node in the list contains a key-value pair.
  • Treeification (Java 8 and above): If a bucket reaches a certain threshold (TREEIFY_THRESHOLD), the linked list is converted into a balanced tree, which improves the worst-case performance from O(n) to O(log n).

Resizing

  • Load Factor and Capacity: The load factor is a measure that decides when to increase the size of the array bac...
junior

junior

Gợi ý câu hỏi phỏng vấn

senior

Explain Boyer-Moore Algorithm with Example in java

senior

What is the basic principle of RMI architecture?

middle

Compare the sleep() and wait() methods in Java

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào