Java treeet throwing illegalArgumentException: key out of range

I removed the code to reproduce the example that causes 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 purpose of the code is to implement some kind of rollover when retrieving subsets of a set. For instance. in the above case, I want all elements c [exclusive] to be 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 two lines, I get

java.lang.IllegalArgumentException: key out of range

+6
source share
1 answer

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 will actually lose the link to the new TreeSet that you created and get a SortedSet that returns set.tailSet .

+7
source

Source: https://habr.com/ru/post/917949/


All Articles