Sobes.tech
Junior — Middle

Can you list different implementations of the Map interface you have worked with?

sobes.tech AI

Answer from AI

In Java, the Map interface has several popular implementations that are commonly used:

  • HashMap — the most common implementation based on a hash table. Provides fast access by key (average O(1)), does not guarantee element order.

  • LinkedHashMap — extends HashMap but maintains insertion order, which is useful if traversal order matters.

  • TreeMap — implements the SortedMap interface, stores elements in sorted order by key, based on a red-black tree. Access and insertion operate in O(log n).

  • ConcurrentHashMap — thread-safe implementation for concurrent access without locking the entire map.

Example of using HashMap:

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

Each implementation is suitable for different tasks depending on requirements for order, performance, and thread safety.