TreeMap——实现comparable接口并重写CompareTo方法
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方法就行了~