Sortedset子列表打印

Sortedset sublist printing

帮我理解一件事。

我创建了一个子列表并打印出来。现在我不明白为什么要打印 "apple" 而 "wind" 不是。如果我写 "aa" 它会按我想要的方式工作,但我想使用 "apple" 来创建子列表,其中 "apple" 不包括在内。这是真的吗?

SortedSet<String> set = new TreeSet<>();
set.add("apple");
set.add("key");
set.add("value");
set.add("roof");
set.add("size");
set.add("wind");

System.out.println(set);
System.out.println(set.subSet("apple","wind"));

输出:

[apple, key, roof, size, value, wind]
[apple, key, roof, size, value]

看看documentation of subSet

Parameters:

  • fromElement - low endpoint (inclusive) of the returned set
  • toElement - high endpoint (exclusive) of the returned set

因此对于 subSet("apple","wind") apple 包含在结果中,但 wind 被排除在外。

如果您希望能够指定应包含或排除哪个端点而不是 SortedSet,您可以使用 NavigableSet 作为参考,其
subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) 方法类似

NavigableSet<String> set = new TreeSet<>(Arrays.asList("apple", "key",
        "value", "roof", "size", "wind"));
System.out.println(set);
System.out.println(set.subSet("apple", false, "wind", false));

输出:

[apple, key, roof, size, value, wind]
[key, roof, size, value]