Junior — Middle
Can you list different ways to implement the Map interface in a programming language?
sobes.tech AI
Answer from AI
In Java (and consequently in Android), the Map interface is implemented by several classes, each suitable for different tasks:
- HashMap — the most common implementation, stores key-value pairs without guaranteed order. Fast insertion and lookup.
- LinkedHashMap — extends HashMap, maintains insertion order.
- TreeMap — implements SortedMap interface, stores elements in sorted order by key (uses a red-black tree).
- ConcurrentHashMap — thread-safe implementation for multi-threaded environments, allows concurrent access without locking the entire map.
- SparseArray (specific to Android) — optimized for mapping int keys to objects, more memory-efficient than HashMap<Integer, Object>.
Example of using HashMap:
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
int count = map.get("apple");