import java.util.*;
public class Explorer1
{
public static void main(String[] args)
{
TreeSet<Integer> s = new TreeSet<Integer>();
TreeSet<Integer> subs = new TreeSet<Integer>();
for(int i = 606; i < 613; i++) if(i%2 == 0) s.add(i);
subs = (TreeSet)s.subSet(608, true, 611, true);
s.add(609);
System.out.println(s + " " + subs);
}
}
O/P: [606, 608, 609, 610, 612] [608, 609, 610]
任何人都可以解释为什么 609 被添加到 subs
中,因为它是在分配给对象之后添加的。
最佳答案
来自 TreeSet 的 JavaDoc...
Returns a view of the portion of this set whose elements range from fromElement to toElement. If fromElement and toElement are equal, the returned set is empty unless fromExclusive and toExclusive are both true. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports.
所以当您执行 s.subSet()
时,您实际上只是获得了 s 的一个 View ,而不是一个全新的 TreeSet。您对 set 所做的任何更改都会反射(reflect)在子集 View 中。
关于java - 树集的工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8426790/