在下面的代码中,我们创建了两个不同的 TreeSet 对象。
我们将一些值分配给第一个对象,然后我们将第一个对象的一个子集分配给第二个对象。然后我们将元素 (609) 添加到第一个对象仅。为什么这个新元素会出现在两个对象中?
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);
}
}
输出:[606, 608, 609, 610, 612] [608, 609, 610]
最佳答案
答案在 documentation 中:
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.
当然,如果你不希望返回集合中的变化反射(reflect)在原始集合中,只需复制一个子集:
subs = new TreeSet<>(s.subSet(608, true, 611, true));
请注意,您的原始代码有一个未经检查的强制转换 操作。你不应该转换为 TreeSet
,但是TreeSet<Integer>
:
subs = (TreeSet<Integer>)s.subSet(608, true, 611, true);
关于java - 向树中添加新元素也会将其添加到树的部分副本中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19354990/