TreeSet higher() method in java

Let’s learn TreeSet higher() method in java.

TreeSet higher() method in java

higher() method of TreeSet class returns the least element in this set strictly greater than the given element, or null if there is no such element.

Syntax:

public E higher(E e)

Parameters:

e the value to match.

Throws:

ClassCastException – if the specified element cannot be compared with the elements currently in the set.

NullPointerException – if the specified element is null and this set uses natural ordering, or its comparator does not permit null elements.

Also read – TreeSet in java

Now let’s see example on TreeSet higher() method.

import java.util.TreeSet;
public class TreeSetHigherMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(9);
      ts.add(4);
      ts.add(6);
      ts.add(2);
      ts.add(10);
      ts.add(3);
      System.out.println(ts.higher(9));
   }
}


Output:

10


Let’s see example on TreeSet higher() method for NullPointerException.

import java.util.TreeSet;
public class TreeSetHigherMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<Integer> ts = new TreeSet<Integer>();
      ts.add(9);
      ts.add(4);
      ts.add(6);
      ts.add(2);
      ts.add(10);
      ts.add(3);
      // pass null to method
      try
      {
         System.out.println(ts.higher(null));
      }
      catch(Exception ex)
      {
         System.out.println(ex);
      }
   }
}


Output:

java.lang.NullPointerException


Here let’s see example on TreeSet higher() method for ClassCastException.

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.TreeSet;
public class TreeSetHigherMethodExample
{
   public static void main(String[] args)
   {
      TreeSet<List> ts = new TreeSet<List>();
      List<Integer> li1 = new LinkedList<Integer>();
      try
      {
         li1.add(2);
         li1.add(4);
         ts.add(li1);
         List<Integer> li2 = new LinkedList<Integer>();
         li2.add(6);
         li2.add(8);
         List<Integer> li3 = new ArrayList<Integer>();
         li2.add(10);
         li2.add(12);
      }
      catch(Exception ex)
      {
         System.out.println(ex);
      }
   }
}


Output:

java.lang.ClassCastException: class java.util.LinkedList cannot be cast to class java.lang.Comparable