EnumSetTreeSet都是定义在集合框架内的类。但它们之间存在着一些区别。在这篇文章中,我们来看看它们之间的区别:

EnumSet

EnumSet是Set接口的一个专门实现,用于枚举类型。它扩展了AbstractSet并实现了Java中的Set接口。EnumSet的几个重要点如下:

  • EnumSet类是Java集合框架的一个成员,它不是同步的。
  • EnumSet中的所有元素都必须来自一个枚举类型,这个枚举类型在创建集合时被明确或隐含地指定。
  • EnumSet比HashSet快得多。
  • EnumSet不允许插入空对象,如果试图插入空对象,它将抛出NullPointerException
  • 它使用了一个故障安全的迭代器,所以如果在迭代过程中集合被修改,它不会抛出ConcurrentModificationException

示例代码

// Java program to demonstrate
// the EnumSet

import java.util.*;
class enumSetExample {
    enum Colors {
        Red,
        Pink,
        Grey,
        Yellow,
        Green
    }
    public static void main(String args[])
    {

        // Creating an EnumSet
        EnumSet<Colors> colors = EnumSet.of(Colors.Pink, Colors.Green);

        Iterator<Colors> itr = colors.iterator();

        // Iterate and print elements to
        // the console
        System.out.println("EnumSet : ");
        while (itr.hasNext()) {
            System.out.println(itr.next());
        }
    }
}

运行结果:

EnumSet : 
Pink
Green

TreeSet

TreeSet是一个在Java中实现SortedSet接口的类。它使用Tree来存储。无论是否提供显式比较器,元素的排序都由集合使用其自然排序来维护。它也可以由一个在集合创建时提供的比较器来排序,这取决于使用哪种构造函数。TreeSet通过继承AbstractSet类实现了一个NavigableSet接口。实现可导航集合的类是一个TreeSet,它是一个自平衡树的实现。因此,这个接口为我们提供了一种在这个树上导航的方法。

示例代码:

// Java code to demonstrate
// the working of TreeSet

import java.util.*;
class TreeSetDemo {

    public static void main(String[] args)
    {
        // Creating an empty TreeSet
        TreeSet<String> ts = new TreeSet<String>();

        // Elements are added using add() method
        ts.add("Yiibai");
        ts.add("For");
        ts.add("Geeks");
    ts.add("welcomes");
    ts.add("you");

        System.out.println("Tree Set is " + ts);

        String check = "welcomes";

        // Check if the above string exists in
        // the treeset or not
        System.out.println("Contains : " + check + " "\n                        + ts.contains(check));

        // Print the first element in
        // the TreeSet
        System.out.println("First Value " + ts.first());

        // Print the last element in
        // the TreeSet
        System.out.println("Last Value " + ts.last());

        String value = "Geek";

        // Find the values just greater
        // and smaller than the above string
        System.out.println("Higher " + ts.higher(value));
        System.out.println("Lower " + ts.lower(value));
    }
}

运行结果:

Tree Set is [For, Yiibai, Geeks, welcomes, you]
Contains : welcomes true
First Value For
Last Value you
Higher Geeks
Lower For

EnumSet和TreeSet的区别 -

属性 EnumSet TreeSet
基本 EnumSet是Set接口的一个专门实现。 TreeSet是java中实现SortedSet接口的一个类。
数据结构 EnumSet在内部表示为一个BitVector。 TreeSet在内部表示为一棵红黑树。
排序 EnumSet按照自然顺序对元素进行排序。 TreeSet根据排序的顺序对元素进行排序。
迭代器 EnumSet迭代器是弱一致性的。 TreeSet迭代器是快速的。
最佳选择 EnumSet是存储枚举类型元素的最佳选择。 TreeSet是存储大量排序信息的最佳选择,因为它的访问和检索时间更快。