代码中是怎么调用compareTo方法的
import java.util.Arrays;
class AlohaPerson implements Comparable<AlohaPerson> {
private String name;
AlohaPerson(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
@Override
public int compareTo(AlohaPerson o) {
return this.name.compareTo(o.name);
}
}
public class Aloha {
public static void sort(AlohaPerson[] persons) {
// 用选择排序法排序
for (int i = 0; i < persons.length - 1; ++i) {
int k = i;
for (int j = k; j < persons.length; ++j) {
// 排序的时候在比较两个对象时用compareTo方法.
if (persons[j].compareTo(persons[k]) < 0) {
k = j;
}
}
if (k != i) {
AlohaPerson temp = persons[k];
persons[k] = persons[i];
persons[i] = temp;
}
}
}
public static void main(String[] args) {
AlohaPerson[] persons = {
new AlohaPerson("Bob"),
new AlohaPerson("John"),
new AlohaPerson("Smith"),
new AlohaPerson("Alpha"),
new AlohaPerson("Beta")
};
System.out.println(Arrays.toString(persons));
sort(persons);
System.out.println(Arrays.toString(persons));
}
}
[Bob, John, Smith, Alpha, Beta]
[Alpha, Beta, Bob, John, Smith]
public boolean add(E e) {
return m.put(e, PRESENT)==null;
}
public V put(K key, V value) {
Entry<K,V> t = root;
if (t == null) {
// TBD:
// 5045147: (coll) Adding null to an empty TreeSet should
// throw NullPointerException
//
// compare(key, key); // type check
root = new Entry<K,V>(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();
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<K,V>(key, value, parent);
if (cmp < 0)
parent.left = e;
else
parent.right = e;
fixAfterInsertion(e);
size++;
modCount++;
return null;
}