关于TreeSet的实现

  TreeSet<String> s = new TreeSet<String>();      //定义并初始化一个String型TreeSet 变量名S
  TreeSet<String>subs = new TreeSet<String>();    //又定义并初始化了一个TreeSet 变量名subs
  s.add("a");        //s中添加字符串"a"
  s.add("b");        //s中添加字符串"b"
  s.add("d");        //s中添加字符串"d"
  s.add("e");        //s中添加字符串"e"

  // 目前s中的元素为a,b,d,e   
  subs = (TreeSet)s.subSet("b",true,"d",true);    //取从b开始到d结束的子集合,包括b,也包括d
  System.out.println(subs + " ");----------------------1
  s.add("9");            //s中添加字符串"9"
  s.add("c2");         //s中添加字符串"c2",目前s中元素为9,a,b,c2,d,e
  s.add("c3");
  TreeSet<String> sub2 = new TreeSet<String>();       //再声明并初始化一个TreeSet
  sub2 = (TreeSet)s.tailSet("c2",true);           //取c2开始到结束的子集合,包括c2
  System.out.println(subs + " " + sub2);//打印一下  ------------2

以上代码为什么在1处输出是[b,d] ,在2处输出[b,c2,c3,d]

TreeSet内部是怎么实现的呢?

TreeSet的源码
[code="java"]
public NavigableSet subSet(E fromElement, boolean fromInclusive,
E toElement, boolean toInclusive) {
return new TreeSet(m.subMap(fromElement, fromInclusive,
toElement, toInclusive));
}
[/code]

subSet方法返回的是同一个对象的引用,只是元素索引位置不一样。
所以在原Set中增加元素,会直接影响到subSet中获取的值。

你得在three里面创建一个添加节点

[quote]TreeSet[/quote]默认已自然排序 比如 a,b,c 1,2,3这样