TreeSet排序丢失记录

 昨天系统用户提示说查询到的记录少了,然后就开始进行各种纠结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默认的比较器进行排序。

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zyz251314

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值