1. /**
    2. * 我们前面提到TreeMap是可以自动排序的,默认情况下comparator为null,这个时候按照key的自然顺序进行排
    3. * 序,然而并不是所有情况下都可以直接使用key的自然顺序,有时候我们想让Map的自动排序按照我们自己的规则,
    4. * 这个时候你就需要传递Comparator的实现类
    5. */
    6. private final Comparator<? super K> comparator;
    1. /**
    2. * TreeMap的存储结构既然是红黑树,那么必然会有唯一的根节点。
    3. */
    4. private transient Entry<K,V> root;
    1. /**
    2. * Map中key-val对的数量,也即是红黑树中节点Entry的数量
    3. */
    4. private transient int size = 0;
    1. /**
    2. * 红黑树结构的调整次数
    3. */
    4. private transient int modCount = 0;
    1. /**
    2. * Node in the Tree. Doubles as a means to pass key-value pairs back to
    3. * user (see Map.Entry).
    4. */
    5. static final class Entry<K,V> implements Map.Entry<K,V> {
    6. //key,val是存储的原始数据
    7. K key;
    8. V value;
    9. //定义了节点的左孩子
    10. Entry<K,V> left;
    11. //定义了节点的右孩子
    12. Entry<K,V> right;
    13. //通过该节点可以反过来往上找到自己的父亲
    14. Entry<K,V> parent;
    15. //默认情况下为黑色节点,可调整
    16. boolean color = BLACK;
    17. /**
    18. * Make a new cell with given key, value, and parent, and with
    19. * {@code null} child links, and BLACK color.
    20. */
    21. Entry(K key, V value, Entry<K,V> parent) {
    22. this.key = key;
    23. this.value = value;
    24. this.parent = parent;
    25. }
    26. /**
    27. * Returns the key.
    28. *
    29. * @return the key
    30. */
    31. public K getKey() {
    32. return key;
    33. }
    34. /**
    35. * Returns the value associated with the key.
    36. *
    37. * @return the value associated with the key
    38. */
    39. public V getValue() {
    40. return value;
    41. }
    42. /**
    43. * Replaces the value currently associated with the key with the given
    44. * value.
    45. *
    46. * @return the value associated with the key before this method was
    47. * called
    48. */
    49. public V setValue(V value) {
    50. V oldValue = this.value;
    51. this.value = value;
    52. return oldValue;
    53. }
    54. public boolean equals(Object o) {
    55. if (!(o instanceof Map.Entry))
    56. return false;
    57. Map.Entry<?,?> e = (Map.Entry<?,?>)o;
    58. return valEquals(key,e.getKey()) && valEquals(value,e.getValue());
    59. }
    60. public int hashCode() {
    61. int keyHash = (key==null ? 0 : key.hashCode());
    62. int valueHash = (value==null ? 0 : value.hashCode());
    63. return keyHash ^ valueHash;
    64. }
    65. public String toString() {
    66. return key + "=" + value;
    67. }
    68. }