java treeset throw illegalArgumentException:key超出范围

Kes*_*115 6 java treeset illegalargumentexception

我已经删除了代码以重现抛出错误的示例:

public class Test {
  public static void main(String[] args) {
    NavigableSet<String> set = new TreeSet<String>(
            Arrays.asList("a", "b", "c", "d"));
    NavigableSet<String> set2 = new TreeSet<String>();
    set2 = set.tailSet("c", false);
    set2.addAll(set.headSet("b", true));
    System.out.println(set2);
  }
}
Run Code Online (Sandbox Code Playgroud)

代码的目的是在检索集合的子集时实现某种翻转.例如,在上面的例子中,我想要c [exclusive]到b [包含]的所有元素.我注意到如果我注释掉tailSet()或headSet()行,其余的代码效果很好.但是,当我有两条线时,我明白了

java.lang.IllegalArgumentException:键超出范围

tib*_*tof 7

尝试这样的事情:

  public static void main(String[] args) {
        NavigableSet<String> set = new TreeSet<String>(
                Arrays.asList("a", "b", "c", "d"));
        NavigableSet<String> set2 = new TreeSet<String>();
        set2.addAll(set.tailSet("c", false));
        set2.addAll(set.headSet("b", true));
        System.out.println(set2);
  }
Run Code Online (Sandbox Code Playgroud)

当你这样做

set2 = set.tailSet("c", false);
Run Code Online (Sandbox Code Playgroud)

你实际上失去了参照新的TreeSet您创建并获得SortedSetset.tailSet返回.