Saturday, 19 April 2014

TreeSet : ceiling : Get Least greater than Element

public E ceiling(E e)
Returns the least element in this set greater than or equal to the given element, or null if there is no such element.

import java.util.*;
class TreeSetCeiling{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements to the set */
  mySet.add(100);
  mySet.add(10);
  mySet.add(120);
  mySet.add(21);
  mySet.add(1);
  mySet.add(-5);
  
  System.out.println("Elements in the set are");
  System.out.println(mySet);
 
  System.out.print("\nCeiling value for 15 is ");
  System.out.println(mySet.ceiling(15));
  System.out.print("Ceiling value for -10 is ");
  System.out.println(mySet.ceiling(-10));
 
 }
}

Output
Elements in the set are
[-5, 1, 10, 21, 100, 120]

Ceiling value for 15 is 21
Ceiling value for -10 is -5 

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

import java.util.*;
class TreeSetCeilingNullPointer{
 public static void main(String args[]){
  TreeSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements to the set */
  mySet.add(100);
  mySet.add(10);
  mySet.add(120);
  mySet.add(21);
  mySet.add(1);
  mySet.add(-5);
  
  System.out.println("Elements in the set are");
  System.out.println(mySet);
 
  System.out.print("\nCeiling value for null is ");
  System.out.println(mySet.ceiling(null));
 
 }
}

Output
Elements in the set are
[-5, 1, 10, 21, 100, 120]

Ceiling value for null is Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1188)
        at java.util.TreeMap.getCeilingEntry(TreeMap.java:390)
        at java.util.TreeMap.ceilingKey(TreeMap.java:747)
        at java.util.TreeSet.ceiling(TreeSet.java:436)
        at TreeSetCeilingNullPointer.main(TreeSetCeilingNullPointer.java:18)







Prevoius                                                 Next                                                 Home

No comments:

Post a Comment