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(ts);
R first=(R) ts.first();
first.count=20;
System.out.println(ts);
R last=(R)ts.last();
last.count=-2;
System.out.println(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);
}为什么只有执行(*)后,即treeSet中元素重新索引后才能删除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(ts);
R first=(R) ts.first();
first.count=20;
System.out.println(ts);
R last=(R)ts.last();
last.count=-2;
System.out.println(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);
}为什么只有执行(*)后,即treeSet中元素重新索引后才能删除TreeSet中所有元素???这个原理是什么??
5
20 -2
-2
第二层节点-2是20的右子节点,因此在删除-2时也即循根搜索-2时一直搜到20的左子节点,搜索为空,因此无法删除待5删除之后,重新平衡了树结构,-2成为根节点,能直接找到所以删除