📅  最后修改于: 2023-12-03 15:35:22.452000             🧑  作者: Mango
Both TreeSet and TreeMap are implementations of the Java Collection Framework. They both implement the SortedSet and SortedMap interfaces respectively. The main difference between these two classes is the data structure they use to store elements.
TreeSet is an implementation of the SortedSet interface in the Java Collection Framework. It uses a tree data structure to maintain the order of elements in the set. The elements are sorted in their natural order or in the order specified by a Comparator that is passed to the constructor of the TreeSet.
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<>();
treeSet.add("apple");
treeSet.add("banana");
treeSet.add("cherry");
treeSet.add("date");
System.out.println(treeSet);
}
}
Output:
[apple, banana, cherry, date]
TreeMap is an implementation of the SortedMap interface in the Java Collection Framework. It uses a tree data structure to maintain the order of elements in the map. The elements are sorted in their natural order or in the order specified by a Comparator that is passed to the constructor of the TreeMap.
import java.util.TreeMap;
public class TreeMapExample {
public static void main(String[] args) {
TreeMap<String, Integer> treeMap = new TreeMap<>();
treeMap.put("apple", 1);
treeMap.put("banana", 2);
treeMap.put("cherry", 3);
treeMap.put("date", 4);
System.out.println(treeMap);
}
}
Output:
{apple=1, banana=2, cherry=3, date=4}
The choice between using TreeSet and TreeMap depends on the specific use case. Use TreeSet if you need to store a unique set of elements in a sorted order. Use TreeMap if you need to store key-value pairs in a sorted order.