Sobes.tech
Junior — Middle

Can you list and explain the key features of the HashMap data structure?

sobes.tech AI

Answer from AI

HashMap is a data structure in Java that stores key-value pairs and provides fast access to values by key.

Key features of HashMap:

  • Fast access: insertion, deletion, and search operations are performed on average in O(1) time thanks to the use of a hash function.
  • Use of hash code: for each key, the hashCode() method is called to determine the index of the bucket in the array.
  • Collision handling: if multiple keys have the same hash, they are stored in a linked list or a tree within a single bucket.
  • Collision resolution: starting from Java 8, when there are many collisions, the linked list is converted into a balanced tree (TreeNode) to improve performance.
  • Order of elements: HashMap does not guarantee the order of elements; to preserve order, LinkedHashMap is used.
  • Null support: one null key and multiple null values are allowed.

Example of creating and using a HashMap:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);

int count = map.get("apple"); // 3
Can you list and explain the key features of the… - sobes.tech