java.util.TreeSet.tailSet(E fromElement, boolean inclusive) - Walking Techie

Blog about Java programming, Design Pattern, and Data Structure.

Sunday, December 18, 2016

java.util.TreeSet.tailSet(E fromElement, boolean inclusive)

What is Java TreeSet

TreeSet creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order according to the natural order. Optionally, you can construct a TreeSet with a constructor that lets you give the collection your own rules for what the order should be (rather than relying on the ordering defined by the elements' class) by using a Comparable or Comparator.

Description of tailSet(E fromElement, boolean inclusive)

The tailSet(E fromElement, boolean inclusive) method returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement. The returned set is backed by this set, so changes in the returned set are reflected in this set, and vice-versa. The returned set supports all optional set operations that this set supports. The returned set will throw an IllegalArgumentException on an attempt to insert an element outside its range.

Declaration

Following is the declaration for java.util.TreeSet.tailSet() method.

public NavigableSet<E> tailSet(E fromElement, boolean inclusive)
Parameters :
  • fromElement -> Low endpoint of the returned set.
  • inclusive -> This is true if the low endpoint is to be included in the returned view.

Return value : Returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement.

Exception :
  • ClassCastException -> If fromElement is not compatible with this set's comparator (or, if the set has no comparator, if fromElement does not implement Comparable).
  • NullPointerException -> If fromElement is null and this set uses natural ordering, or its comparator does not permit null elements.
  • IllegalArgumentException -> If this set itself has a restricted range, and fromElement lies outside the bounds of the range.

Simple example of TreeSet.tailSet(E fromElement, boolean inclusive)

The following example shows the usage of java.util.TreeSet.tailSet() method.

package com.walking.techie;

import java.util.TreeSet;

public class TreeSetTailSet {

    public static void main(String[] args) {
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(23);
        treeSet.add(34);
        treeSet.add(13);
        treeSet.add(2);
        treeSet.add(28);

        // printing the elements of tree set using for-each
        System.out.println("***Elements of the treeSet***");
        for (Integer val : treeSet) {
            System.out.println(val);
        }

        // creating set whose values greater than 13
        TreeSet<Integer> treeTailSet = (TreeSet<Integer>)
                treeSet.tailSet(13, false);

        // printing the elements of the treeTailSet
        System.out.println("***Elements of the treeTailSet" +
                                         " greater than 13 ***");
        for (Integer val : treeTailSet) {
            System.out.println(val);
        }

        treeTailSet = (TreeSet<Integer>) treeSet.tailSet(13, true);
        // printing the elements of the treeTailSet
        System.out.println("***Elements of the treeTailSet " +
                             "greater than or equal to 13 ***");
        for (Integer val : treeTailSet) {
            System.out.println(val);
        }
    }
}

Output of above program is shown below:

***Elements of the treeSet***
2
13
23
28
34
***Elements of the treeTailSet greater than 13 ***
23
28
34
***Elements of the treeTailSet greater than or equal to 13 ***
13
23
28
34

java.util.TreeSet.tailSet(E fromElement, boolean inclusive) with ConcurrentModificationException

The tailSet(E fromElement, boolean inclusive) method returns a view of the portion of this set whose elements are greater than (or equal to, if inclusive is true) fromElement. The returned is backed by this set, changes in the returned set are reflected in this set, and vice-versa. while iterating over set if either set is modified then ConcurrentModificationException. In below program, you can see while iterating over set using for-each, any modification in either set will throw ConcurrentModificationException.

You can also see the code using the TreeSet's iterator() method by uncommenting in below code and comment for-each part. Once you create an iterator over either set, any modification on either set while iterating over set will throw ConcurrentModificationException.

package com.walking.techie;

import java.util.TreeSet;
import java.util.Iterator;


public class TreeSetTailSetConcurrentModificationException {

    public static void main(String[] args) {
        // create an empty tree set
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(23);
        treeSet.add(34);
        treeSet.add(2);
        treeSet.add(21);
        treeSet.add(45);
        treeSet.add(15);

        // printing the elements of tree set using for-each
        System.out.println("***Elements of the treeSet***");
        for (Integer val : treeSet) {
            System.out.println(val);
        }

        // creating set whose values greater than or equal to 13
        TreeSet<Integer> treeTailSet = (TreeSet<Integer>)
                         treeSet.tailSet(13, true);

        System.out.println("***Elements of the treeTailSet***");
        System.out.println(treeTailSet);

        for (Integer val : treeSet) {
            if (val == 21) {
                treeTailSet.add(20);// ConcurrentModificationException
            }
        }

   // create an iterator of treeTailSet
        /*Iterator<Integer> iterator = treeTailSet.iterator();
        while (iterator.hasNext()) {
            Integer val = iterator.next();
            if (val == 21) {
                treeSet.add(40); // ConcurrentModificationException
            }
        }*/
    }
}

Output of above program is shown below:

***Elements of the treeSet***
2
15
21
23
34
45
***Elements of the treeTailSet***
[15, 21, 23, 34, 45]
Exception in thread "main" java.util.ConcurrentModificationException
 at java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1211)
 at java.util.TreeMap$KeyIterator.next(TreeMap.java:1265)
 at com.walking.techie.TreeSetTailSetConcurrentModificationException.main(TreeSetTailSetConcurrentModificationException.java:32)

java.util.TreeSet.tailSet(E fromElement, boolean inclusive) with IllegalArgumentException

The set returned by tailSet(E fromElement, boolean inclusive) method call, and modified the returned set, If this set itself has a restricted range, and fromElement lies outside the bounds of the range, then it will throw IllegalArgumentException.

package com.walking.techie;

import java.util.TreeSet;


public class TreeSetTailSetIllegalArgumentException2 {

    public static void main(String[] args) {
        // create an empty tree set
        TreeSet<Integer> treeSet = new TreeSet<Integer>();
        treeSet.add(23);
        treeSet.add(34);
        treeSet.add(2);
        treeSet.add(21);
        treeSet.add(45);
        treeSet.add(15);

        TreeSet<Integer> treeTailSet = (TreeSet<Integer>) treeSet.tailSet(15, true);

        // printing the elements of tree set
        System.out.println("***Elements of the treeSet***");
        System.out.println(treeSet);
        System.out.println("***Elements of the treeTailSet***");
        System.out.println(treeTailSet);

        // 20 is greater than or equal to 15 (key boundary)
        treeTailSet.add(20);//not throw IllegalArgumentException
        System.out.println("***Elements of the modified treeTailSet***");
        System.out.println(treeTailSet);

        //adding element should be less than key boundary
        treeTailSet.add(12);//throw IllegalArgumentException
        System.out.println("***Elements of the modified treeTailSet***");
        System.out.println(treeTailSet);
    }
}

Output of above program is shown below:

***Elements of the treeSet***
[2, 15, 21, 23, 34, 45]
***Elements of the treeTailSet***
[15, 21, 23, 34, 45]
***Elements of the modified treeTailSet***
[15, 20, 21, 23, 34, 45]
Exception in thread "main" java.lang.IllegalArgumentException: key out of range
 at java.util.TreeMap$NavigableSubMap.put(TreeMap.java:1516)
 at java.util.TreeSet.add(TreeSet.java:255)
 at com.walking.techie.TreeSetTailSetIllegalArgumentException2.main(TreeSetTailSetIllegalArgumentException2.java:32)

No comments :

Post a Comment