📜  treeset vs treemap (1)

📅  最后修改于: 2023-12-03 15:35:22.452000             🧑  作者: Mango

TreeSet vs TreeMap

Introduction

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

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.

Characteristics of TreeSet
  • TreeSet does not allow duplicate elements.
  • TreeSet elements are stored in a sorted order.
  • TreeSet provides efficient operations for adding, removing, and retrieving elements from the set.
  • TreeSet does not maintain insertion order.
Example usage of 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

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.

Characteristics of TreeMap
  • TreeMap keys are sorted in a sorted order.
  • Duplicate keys are not allowed in TreeMap.
  • TreeMap provides efficient operations for adding, removing, and retrieving elements from the map.
  • TreeMap does not maintain insertion order.
Example usage of 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}
Conclusion

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.