6

我已经剥离了代码以重现引发错误的示例:

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);
  }
}

代码的目的是在检索集合的子集时实现某种翻转。例如,在上述情况下,我想要从 c [exclusive] 到 b [inclusive] 的所有元素。我注意到,如果我注释掉 tailSet() 或 headSet() 行,其余代码运行良好。但是,当我有两条线时,我得到

java.lang.IllegalArgumentException:键超出范围

4

1 回答 1

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);
  }

当你这样做

set2 = set.tailSet("c", false);

您实际上失去了对TreeSet您创建的新的引用并获得返回的SortedSet引用。set.tailSet

于 2012-06-13T09:32:32.297 回答