简体   繁体   中英

How to get IllegalArgumentException while fetching values from tree set?

As per the tailset definition

"A tailSet() method of TreeSet class returns the element present in the set, which is greater than or equal to fromElement. If the passed value is outside of the range, an IllegalArgumentException is thrown"

but when i am trying to implement it, its returning blank set instead of throwing IllegalArgumentException.

public class SampleSet {

    public static void main(String[] args) {

        NavigableSet obj = new TreeSet();
        NavigableSet obj1 = new TreeSet();
        obj.add(4);
        obj.add(6);
        obj.add(9);
        obj.add(2);
        System.out.println(obj);
        obj1 = (NavigableSet) obj.tailSet(9,false);
        System.out.println(obj1);
    }

}

Please explain what is the way to get IllegalArgumentException while fetching. Thanks in advance.

I used your code as a basis. The range can be determined by a subSet() (javaDoc) :

NavigableSet<E> subSet​(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

Using tailSet() on this subset with an out-of-range value will cause an IllegalArgumentException :

import java.util.NavigableSet;

public class Testing {

    public static void main(String[] args) {

        NavigableSet<Integer> obj = new TreeSet<>();
        NavigableSet<Integer> obj1 = new TreeSet<>();
        obj.add(4);
        obj.add(6);
        obj.add(9);
        obj.add(2);
        System.out.println(obj);
        obj1 = obj.tailSet(9,false);
        System.out.println(obj1);

        obj1 = obj.subSet(4, true, 6, true);
        obj1 = obj1.tailSet(9,false);       // 9 is out of range

    }
}

Result:

[2, 4, 6, 9]
[]
Exception in thread "main" java.lang.IllegalArgumentException: fromKey out of range
        at java.base/java.util.TreeMap$AscendingSubMap.tailMap(TreeMap.java:1880)
        at java.base/java.util.TreeSet.tailSet(TreeSet.java:350)
        at Testing.main(Testing.java:989)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM