Junior — Middle
Describe the main types of data structures that implement key-value mapping.
sobes.tech AI
Answer from AI
The main types of data structures implementing key-value mapping (Map) include:
- HashMap — implements mapping based on a hash table. Fast access to elements (average O(1)), but the order of elements is not guaranteed.
- TreeMap — implements mapping based on a balanced tree (e.g., red-black). Elements are ordered by key, and operations have a complexity of O(log n).
- LinkedHashMap — combines a hash table and a linked list, preserving the insertion order of elements.
Example of using HashMap in Java:
import java.util.HashMap;
HashMap<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
int count = map.get("apple"); // 3
Each of these structures is suitable for different tasks depending on requirements for order and performance.