java - 树集的工作

标签 java

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/

相关文章:

java - 使用一对多关系时,有没有办法控制子实体的顺序?

Java hashmap int 不能被取消引用

java - svg-android 库中 getDeclaredField() 上的 Android 6.0 (Marshmallow) 静态初始化异常

使用 Int 的 Java jSF NamedQuery

enums - Java 枚举单例的注解

java - 在 Java 中将 Pi 计算为特定数量的项?

java - 如何强制 fge json-schema validator 对未知关键字抛出错误?

java - 从 Path 中捕获元素

java - Android 中的倒计时器

java - 如何用GSON解析这个JSON字符串?