Difference between TreeMap and TreeSet in Java - TongtongLan/Java GitHub Wiki

要记住关于 TreeMap 和 TreeSet 的关键点是它们使用 compareTo()compare() 方法来比较对象,所以如果使用在 Integers 的 TreeSet 中放置一个 String 对象, add() 方法会在 Java 5之前的版本运行时抛出 ClassCastException, 在Java 5之后,可以使用泛型来通过声明TreeMap和TreeSet参数化版本来避免这种情况的发生。

Similarities between TreeMap and TreeSet in Java

  1. 都具有排序功能(可自定义排序方法)

Both TreeMap and TreeSet are sorted data structure, which means they keep there element in predefined Sorted order. Sorting order can be natural sorting order defined by Comparable interface or custom sorting Order defined by Comparator interface. Both TreeMap and TreeSet has overloaded constructor which accept a Comparator, if provided all elements inside TreeSet or TreeMap will be compared and Sorted using this Comparator.

  1. 都实现了基本接口

TreeSet implements Collection and Set interface so that they can be passed to method where a Collection is expected and TreeMap implements java.util.Map interface, which means you can pass it when a Map is expected.

  1. 底层实现相同,TreeSet类是通过调用TreeMap方法实现的

TreeSet is practically implemented using TreeMap instance, similar to HashSet which is internally backed by HashMap instance. See Internal Implementation of HashSet to learn more.

  1. 都是非线程同步的,不能被多个线程共享

Both TreeMap and TreeSet are non synchronized Collection, hence can not be shared between multiple threads. You can make both TreeSet and TreeMap synchronized by wrapping them into Synchronized collection by calling Collections.synchroinzedMap() method.

  1. 迭代器都是fail-fast的

this means they will throw ConcurrentModificationException when TreeMap or TreeSet is modified structurally once Iterator is created. this fail-fast behavior is not guaranteed but works in best effort.

  1. 比HashSet及HashMap在add, remove and get等一些操作上慢

Both TreeMap and TreeSet are slower than there Hash counter part like HashSet and HashMap and instead of providing constant time performance for add, remove and get operation they provide performance in O(log(n)) order.

Differences between TreeSet vs TreeMap in Java:

  1. 实现的底层接口不同

Major difference between TreeSet and TreeMap is that TreeSet implements Set interface while TreeMap implements Map interface in Java.

  1. 存储对象的方式不同,排序的对象也不同

Second difference between TreeMap and TreeSet is the way they store objects. TreeSet stores only one object while TreeMap uses two objects called key and Value. Objects in TreeSet are sorted while keys in TreeMap remain in sorted Order.

  1. TreeSet实现了NavigableSet, TreeMap实现了 NavigableMap

  2. TreeMap中允许重复值

Fourth difference is that duplicate objects are not allowed in TreeSet but duplicates values are allowed in TreeMap.

Read more: http://www.java67.com/2012/08/difference-between-treemap-and-treeset-java.html#ixzz518A6BGVa