Junior — Middle
What is the difference between using TreeSet and TreeMap in Java collections?
sobes.tech AI
Answer from AI
TreeSet and TreeMap are collections from Java based on red-black trees, which store elements in sorted order.
-
TreeSet is a set that stores unique elements without keys. It is implemented based on TreeMap, where elements act as keys, and default values are a placeholder constant.
-
TreeMap is a map that stores key-value pairs, where keys are sorted either by their natural order or with the help of a Comparator.
Summary:
- TreeSet stores only unique elements (as keys), without associating them with any values.
- TreeMap stores key-value pairs, allowing quick lookup of values by key.
Example usage:
TreeSet<String> set = new TreeSet<>();
set.add("apple");
set.add("banana");
TreeMap<String, Integer> map = new TreeMap<>();
map.put("apple", 1);
map.put("banana", 2);