import java.util.*;
class MyComp implements Comparator<String>{
public int compare(String aStr, String bStr) {
return bStr.compareTo(aStr);
}
}
public class CustomComparatorTest {
public static void main(String[] args) {
MyComp my = new MyComp();
TreeSet<String> ts = new TreeSet<String>(my);
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("Y");
ts.add("T");
ts.add("W");
for(String element : ts)
{
System.out.println(element + " ");
}
System.out.println();
}
}
答案 0 :(得分:3)
假设你问的是如何在没有在main方法中显式调用的情况下执行compare方法,每次向其添加元素时都会通过TreeSet
代码调用它,以便在TreeSet
应该存储元素。这种方式TreeSet
维护元素按照您传递给构造函数的Comparator
所规定的顺序排序。
答案 1 :(得分:1)
public boolean add(E e) {return m.put(e, PRESENT)==null;}
当你调用 add(x)函数时,在TreeSet中调用 TreeMap.put()方法,在 TreeMap.put()中,它将调用比较器。像这样的源代码:
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();
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;
}