Search code examples
javaillegalargumentexceptiontreeset

java treeset throwing illegalArgumentException: key out of range


I've stripped down the code to reproduce an example which throws the error:

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

The aim of the code is to implement some sort of rollover when retrieving subsets of the set. E.g. in the case above, I want all elements from c [exclusive] to b [inclusive]. I noticed that if I comment out the tailSet() or headSet() lines, the rest of the code works well. However, when I have both lines, I get

java.lang.IllegalArgumentException: key out of range


Solution

  • Try something like this:

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

    When you do

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

    you actually lose the reference to the new TreeSet that you created and get the SortedSet that set.tailSet returns.