昨天系统用户提示说查询到的记录少了,然后就开始进行各种纠结ing,查找源码,各种debug最后发现是在进入放入TreeSet的时候丢失了。
以下是定义的TreeSet
Set<Bill> set = new TreeSet<Bill>(new Comparator<Bill>() {
public int compare(Bill o1, Bill o2)
{
String shopNo1 = o1.getShopSysNo();
String shopNo2 = o2.getShopSysNo();
if (shopNo1.compareTo(shopNo2) > 0)
return 1;
else if (shopNo1.compareTo(shopNo2) < 0)
return -1;
else if (shopNo1.compareTo(shopNo2) == 0) {
String clearDate1 = o1.getClearDate();
String clearDate2 = o2.getClearDate();
return clearDate1.compareTo(clearDate2);
}
return 0;
}
});
然后开始查看TreeSet的Add()的源码
public boolean add(E e) {return m.put(e, PRESENT)==null;}
发现底层调用了TreeMap的put方法,继续追踪:
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;
}
发现当调用TreeSet的add()方法时,在TreeSet的内部会间接调用compareTo()方法、然后和TreeSet中已经存在的其他元素一一进行比较,在比较的过程中完成“判断是否重复”以及“排序”的功能:当在某次比较的过程中发现compareTo()返回0,就会认为待加入的元素已经存在于TreeSet中,返回-1或1的话就会根据TreeSet默认的比较器进行排序。