public class TreeMapTest { public static void main(String[] args) { Map<Student,Integer> students = new TreeMap<>(); students.put(new Student("11"),1); students.put(new Student("11"),1); System.out.println(students.size()); } }
輸出結果為2
因為
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; modCount++; return null; } int cmp; Entry<K,V> parent; // split comparator and comparable paths Comparator<? super K> cpr = comparator; if (cpr != null) { do { parent = t; cmp = cpr.compare(key, t.key); if (cmp < 0) t = t.left; else if (cmp > 0) t = t.right; else 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) t = t.left; else if (cmp > 0) t = t.right; else return t.setValue(value); } while (t != null); } Entry<K,V> e = new Entry<>(key, value, parent); if (cmp < 0) parent.left = e; else parent.right = e; fixAfterInsertion(e); size++; modCount++; return null; }
上面紅色字體:調用compareTo方法,看結果來看新存入的值放在左側(cmp<0),還是右側(cmp>0),還是現在的value值把原來的value值覆蓋(cmp=0)
需要在Student類中重寫compareTo方法
@Override public int compareTo(Student o) { return 0; }
按照你自己的要求重寫compareTo方法就行了~