TreeSet是以自然順序存的數據,例如
Set<Student> students=new TreeSet(); students.add(new Student("111")); students.add(new Student("333")); students.add(new Student("222")); for (Student student : students) { System.out.println(student.getId()); }
輸出結果為111 222 333
而且這時候的Student必須繼承Comparable接口,重寫抽象方法CompareTo方法
public class Student implements Comparable<Student> { private String id; public Student(String id) { this.id = id; } @Override public int compareTo(Student o) { return 1; } }
出現這樣的效果是因為存儲的時候的代碼是這樣的
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方法,這個時候就會判斷你存的值得大小順序,然后判斷你該存儲的順序,就是自然順序了。。