Java 中树集和哈希集的区别

javaobject oriented programmingprogramming更新于 2025/2/26 10:20:17

哈希集和树集都属于集合框架。HashSet 是 Set 接口的实现,而树集实现了有序集。树集由 TreeMap 支持,而 HashSet 由 hashmap 支持。

Sr.号Key哈希集树集
1
实现 
哈希集使用 HashTable 实现 
树集使用树实现结构。 
2
空对象 
HashSet 允许空对象 
树集合不允许空对象。抛出空指针异常。 
3
方法 
哈希集使用equals方法比较两个对象 
树集使用compare方法比较两个对象。 
4
异构对象
哈希集现在不允许异构对象
树集允许异构对象
5
排序 
HashSet 不维护任何顺序 
TreeSet 维护按排序顺序排列的对象 

TreeSet 示例

class TreeSetExmaple {
   public static void main(String[] args){
      TreeSet<String> treeset = new TreeSet<String>();
      treeset.add("Good");
      treeset.add("For");
      treeset.add("Health");
      //Add Duplicate Element
      treeset.add("Good");
      System.out.println("TreeSet : ");
      for (String temp : treeset) {
         System.out.println(temp);
      }
   }
}

输出

TreeSet:
   For
   Good
   Health

Example of HashSet

class HashSetExample {
   public static void main(String[] args){
      HashSet<String> hashSet = new HashSet<String>();
      hashSet.add("Good");
      hashSet.add("For");
      hashSet.add("Health");
      //Add Duplicate Element
      hashSet.add("Good");
      System.out.println("HashSet: ");
      for (String temp : hashSet) {
         System.out.println(temp);
      }
   }
}

输出

HashSet:
   Health
   For
   Good


相关文章


有用资源