Sobes.tech
Junior

Tell me about the HashMap class and its main features in Java.

sobes.tech AI

Answer from AI

HashMap in Java is an implementation of the Map interface, representing an unordered collection of key-value pairs. It is based on a hash table.

Main characteristics:

  • Unordered: The order of elements in HashMap is not guaranteed and can change over time.
  • No duplicate keys: Each key in HashMap must be unique. If you try to add an element with an existing key, the old value will be replaced with the new one.
  • Null values and one null key are allowed: HashMap can contain one null key and multiple null values.
  • Performance: Operations like add, remove, and get by key (put, remove, get) have an average complexity of O(1) with a uniform hash code distribution. In the worst case (e.g., very poor hash function or many collisions), the complexity can reach O(n).
  • Not synchronized: HashMap is not thread-safe. For use in multithreaded environments, it is recommended to use ConcurrentHashMap or wrap HashMap with Collections.synchronizedMap().
  • Uses equals() and hashCode(): HashMap uses these methods to determine key equality and compute hash table indices. Proper implementation of these methods is crucial for HashMap's correct operation.

Data structure:

HashMap uses an array of buckets, each of which can contain multiple elements. The bucket index is determined by the hash code of the key. Collisions (different keys with the same hash code) are handled by storing elements in a linked list or, since Java 8, a balanced tree (red-black tree) if the number of elements exceeds a threshold (TREEIFY_THRESHOLD).

Example usage:

// Creating HashMap
HashMap<String, Integer> ages = new HashMap<>();

// Adding elements
ages.put("Alice", 30);
ages.put("Bob", 25);
ages.put("Charlie", 35);

// Getting value by key
int bobAge = ages.get("Bob"); // bobAge = 25
Tell me about the HashMap class and its main features… - sobes.tech