关于 put 方法

源码

1、put

  1. public V put(K key, V value) {
  2. Entry<K,V> t = root;
  3. if (t == null) {
  4. compare(key, key); // type (and possibly null) check
  5. root = new Entry<>(key, value, null);
  6. size = 1;
  7. modCount++;
  8. return null;
  9. }
  10. int cmp;
  11. Entry<K,V> parent;
  12. // split comparator and comparable paths
  13. Comparator<? super K> cpr = comparator;
  14. if (cpr != null) {
  15. do {
  16. parent = t;
  17. cmp = cpr.compare(key, t.key);
  18. if (cmp < 0)
  19. t = t.left;
  20. else if (cmp > 0)
  21. t = t.right;
  22. else
  23. return t.setValue(value);
  24. } while (t != null);
  25. }
  26. else {
  27. if (key == null)
  28. throw new NullPointerException();
  29. @SuppressWarnings("unchecked")
  30. Comparable<? super K> k = (Comparable<? super K>) key;
  31. do {
  32. parent = t;
  33. cmp = k.compareTo(t.key);
  34. if (cmp < 0)
  35. t = t.left;
  36. else if (cmp > 0)
  37. t = t.right;
  38. else
  39. return t.setValue(value);
  40. } while (t != null);
  41. }
  42. Entry<K,V> e = new Entry<>(key, value, parent);
  43. if (cmp < 0)
  44. parent.left = e;
  45. else
  46. parent.right = e;
  47. fixAfterInsertion(e);
  48. size++;
  49. modCount++;
  50. return null;
  51. }

2、put 源码注释

  1. public V put(K key, V value) {
  2. Entry<K,V> t = root;
  3. if (t == null) {
  4. compare(key, key); // type (and possibly null) check
  5. root = new Entry<>(key, value, null);
  6. size = 1;
  7. modCount++;
  8. return null;
  9. }
  10. int cmp;
  11. Entry<K,V> parent;
  12. // split comparator and comparable paths
  13. Comparator<? super K> cpr = comparator;
  14. if (cpr != null) {
  15. do {
  16. parent = t;
  17. cmp = cpr.compare(key, t.key);
  18. if (cmp < 0)
  19. t = t.left;
  20. else if (cmp > 0)
  21. t = t.right;
  22. else
  23. return t.setValue(value);
  24. } while (t != null);
  25. }
  26. else {
  27. if (key == null)
  28. throw new NullPointerException();
  29. @SuppressWarnings("unchecked")
  30. Comparable<? super K> k = (Comparable<? super K>) key;
  31. do {
  32. parent = t;
  33. cmp = k.compareTo(t.key);
  34. if (cmp < 0)
  35. t = t.left;
  36. else if (cmp > 0)
  37. t = t.right;
  38. else
  39. return t.setValue(value);
  40. } while (t != null);
  41. }
  42. Entry<K,V> e = new Entry<>(key, value, parent);
  43. if (cmp < 0)
  44. parent.left = e;
  45. else
  46. parent.right = e;
  47. fixAfterInsertion(e);
  48. size++;
  49. modCount++;
  50. return null;
  51. }