JAVA8 TreeMap學習筆記

TreeMap

TreeMap集合是基于紅黑樹(Red-Black tree)的 NavigableMap實現。該集合最重要的特點就是可排序,該映射根據其鍵的自然順序進行排序,或者根據創建映射時提供的 Comparator 進行排序,具體取決于使用的構造方法。這句話是什么意思呢?就是說TreeMap可以對添加進來的元素進行排序,可以按照默認的排序方式,也可以自己指定排序方式

【知識點】

  • TreeMap基于紅黑樹實現無容量限制;
  • TreeMap是非線程安全的;

類名及類成員變量

public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, java.io.Serializable
{
// 比較器對象
private final Comparator<? super K> comparator;

// 根節點
private transient Entry<K,V> root;

// 集合大小
private transient int size = 0;

// 樹結構被修改的次數
private transient int modCount = 0;

// 靜態內部類用來表示節點類型
static final class Entry<K,V> implements Map.Entry<K,V> {
K key; // 鍵
V value; // 值
Entry<K,V> left; // 指向左子樹的引用(指針)
Entry<K,V> right; // 指向右子樹的引用(指針)
Entry<K,V> parent; // 指向父節點的引用(指針)
boolean color = BLACK; //
}
}

類構造方法

public TreeMap() { // 1,無參構造方法
comparator = null; // 默認比較機制
}

public TreeMap(Comparator<? super K> comparator) { // 2,自定義比較器的構造方法
this.comparator = comparator;
}

public TreeMap(Map<? extends K, ? extends V> m) { // 3,構造已知Map對象為TreeMap
comparator = null; // 默認比較機制
putAll(m);
}

public TreeMap(SortedMap<K, ? extends V> m) { // 4,構造已知的SortedMap對象為TreeMap
comparator = m.comparator(); // 使用已知對象的構造器
try {
buildFromSorted(m.size(), m.entrySet().iterator(), null, null);
} catch (java.io.IOException cannotHappen) {
} catch (ClassNotFoundException cannotHappen) {
}
}
  • put(K key, V value)
public V put(K key, V value) {
Entry<K,V> t = root; // 獲取根節點

// 如果根節點為空,則該元素置為根節點
if (t == null) {
compare(key, key); // type (and possibly null) check

root = new Entry<>(key, value, null);
size = 1; // 集合大小為1
modCount++; // 結構修改次數自增
return null;
}

int cmp;
Entry<K,V> parent;
Comparator<? super K> cpr = comparator; // 比較器對象

// 如果比較器對象不為空,也就是自定義了比較器
if (cpr != null) {
do { // 循環比較并確定元素應插入的位置(也就是找到該元素的父節點)
parent = t; // t就是root

// 調用比較器對象的compare()方法,該方法返回一個整數
cmp = cpr.compare(key, t.key);
if (cmp < 0) // 待插入元素的key"小于"當前位置元素的key,則查詢左子樹
t = t.left;
else if (cmp > 0) // 待插入元素的key"大于"當前位置元素的key,則查詢右子樹
t = t.right;
else // "相等"則替換其value。
return t.setValue(value);
} while (t != null);
}

// 如果比較器對象為空,使用默認的比較機制
else {
if (key == null)
throw new NullPointerException();
@SuppressWarnings("unchecked")
Comparable<? super K> k = (Comparable<? super K>) key; // 取出比較器對象
do { // 同樣是循環比較并確定元素應插入的位置(也就是找到該元素的父節點)
parent = t;
cmp = k.compareTo(t.key); // 同樣調用比較方法并返回一個整數
if (cmp < 0) // 待插入元素的key"小于"當前位置元素的key,則查詢左子樹
t = t.left;
else if (cmp > 0) // 待插入元素的key"大于"當前位置元素的key,則查詢右子樹
t = t.right;
else // "相等"則替換其value。
return t.setValue(value);
} while (t != null);
}

Entry<K,V> e = new Entry<>(key, value, parent); // 根據key找到父節點后新建一個節點
if (cmp < 0) // 根據比較的結果來確定放在左子樹還是右子樹
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++; // 集合大小+1
modCount++; // 集合結構被修改次數+1
return null;
}

自定義比較器

  1. key為String類型,因為String實現了Comparable接口,所以按照String類中的compareTo方法進行排序;
  2. TreeMap的key實現Comparable接口并實現compareTo方法;
public class User implements Comparable<User>{
private String username;
private int age;

public User(String username, int age) {
this.username = username;
this.age = age;
}

@Override
public String toString() {
return "User [username=" + username + ", age=" + age + "]";
}
@Override
public int compareTo(User user) {
int temp = this.age - user.age;
return temp == 0 ? this.username.compareTo(user.username) : temp;
}
}
  1. 使用TreeMap的構造方法傳遞比較器
Map<User3, String> map = new TreeMap<>(new TreeMapComparator());
  1. 使用匿名內部類的形式來寫比較器
Map<User3, String> map = new TreeMap<>(new Comparator<User3>() {

@Override
public int compare(User3 o1, User3 o2) {
int temp = o1.getAge() - o2.getAge();
return temp == 0 ? o1.getUsername().compareTo(o2.getUsername()) : temp;
}
});

參考資料

http://www.lxweimin.com/p/69f11fc9ea38

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容