Junior — Middle
What are the differences between Collection and Map interfaces in Java, and why are they needed?
sobes.tech AI
Answer from AI
Collection and Map are two main interfaces in Java for working with collections, but they serve different purposes:
-
Collection is a basic interface for groups of objects that can be iterated over. It includes lists (List), sets (Set), and queues (Queue). The main idea is to store a set of elements, where each element is an object.
-
Map is a data structure for storing pairs of "key-value". It does not inherit from Collection because it is not just a set of elements, but a mapping of keys to values.
Uses:
- Collection is convenient when working with a set of elements, for example, a list of users or a set of unique values.
- Map is needed when you want to quickly find a value by its key, for example, storing settings by parameter name.
Example:
// Collection example
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
// Map example
Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);
System.out.println(list.get(0)); // apple
System.out.println(map.get("banana")); // 5