关于TreeSet添加元素后删除- 创意小软件开发要塞- JavaEye技术网站

??? 知道TreeSet的backing map是TreeMap,看程序:

import java.util.TreeSet;

class R implements Comparable<Object> {
	int count;

	public R(int count) {
		this.count = count;

	}

	public String toString() {
		return "R(count:" + count + ")";

	}

	public boolean equals(Object o) {
		if (o instanceof R) {
			R r = (R) o;
			if (this.count == r.count)
				return true;
		}
		return false;
	}

	public int compareTo(Object o) {
		R r = (R) o;
		if (this.count > r.count)
			return 1;
		else if (this.count == r.count)
			return 0;
		else
			return -1;
	}
}

public class TestTreeSetError {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		TreeSet<R> ts = new TreeSet<R>();
		ts.add(new R(5));
		ts.add(new R(-3));
		ts.add(new R(9));
		ts.add(new R(-2));
		System.out.println("1 = " + ts);
		R first = (R) ts.first();
		first.count = 20;
		System.out.println("2 = " + ts);
		R last = (R) ts.last();
		last.count = -2;
		System.out.println("3 = " + ts);
		System.out.println(ts.remove(new R(-2)));
		System.out.println(ts);
		System.out.println(ts.remove(new R(5)));
		System.out.println(ts);
		System.out.println(ts.remove(new R(-2)));
		System.out.println(ts);

	}
}

?

树添加修改稳定之后,形成的红黑树是这样的:

????????? 5

20????????????? -2
????? -2

第二层-2是20的右子节点,因为删除时循根搜索,-2一直往左路搜,{zh1}搜到20左子节点为空,所以删除失败,待5删除之后,重新平衡了树结构:

???? -2

20????? -2

因此-2就能被删除

?

这其中涉及到了TreeSet中的remove:

public boolean remove(Object o) {
    return m.remove(o)==PRESENT;
}

?

TreeMap中的remove:

public V remove(Object key) {
        Entry<K,V> p = getEntry(key);
        if (p == null)
            return null;

        V oldValue = p.value;
        deleteEntry(p);
        return oldValue;
}

?

最终到TreeMap的getEntry:

final Entry<K,V> getEntry(Object key) {
        // Offload comparator-based version for sake of performance
        if (comparator != null)
            return getEntryUsingComparator(key);
        if (key == null)
            throw new NullPointerException();
	Comparable<? super K> k = (Comparable<? super K>) key;
        Entry<K,V> p = root;
        while (p != null) {
            int cmp = k.compareTo(p.key);
            if (cmp < 0)
                p = p.left;
            else if (cmp > 0)
                p = p.right;
            else
                return p;
        }
        return null;
}
?

? 添加时涉及到代码略

{zx1}评论

  • 谢谢你的回复,在你启发下我去debug了下程序,的确只有在read()方法的时候当 ...
    -- by

  • 回楼下huayurei:??? 原来的认识是有问题的, 看BufferedRead ...
    -- by

  • wentao365 写道 return obj; 是不是写错了?这里retur ...
    -- by

  • 这个解释是有可能会引起异常,偏偏我怎么设置都不产生异常,搞了我半天都没明白这个ma ...
    -- by

  • return obj; 是不是写错了?
    -- by
郑重声明:资讯 【关于TreeSet添加元素后删除- 创意小软件开发要塞- JavaEye技术网站】由 发布,版权归原作者及其所在单位,其原创性以及文中陈述文字和内容未经(企业库qiyeku.com)证实,请读者仅作参考,并请自行核实相关内容。若本文有侵犯到您的版权, 请你提供相关证明及申请并与我们联系(qiyeku # qq.com)或【在线投诉】,我们审核后将会尽快处理。
—— 相关资讯 ——