TreeSet——实现Comparable接口并重写CompareTo()方法

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方法,这个时候就会判断你存的值得大小顺序,然后判断你该存储的顺序,就是自然顺序了。。

上一篇:Java compareTo() 方法(转载)


下一篇:elementui上传文件