Monday 21 April 2014

NavigableSet : floor

E floor(E e)
return the greatest element less than or equal to e,or null if there is no such element.

import java.util.*;

class NavigableSetFloor{
 public static void main(String args[]){
  NavigableSet<Integer> mySet = new TreeSet<> ();
  
  for(int i=20; i >0; i-=2)
   mySet.add(i);
   
  System.out.println("Elements in mySet are");
  System.out.println(mySet+"\n");
  
  for(int i =1; i <= 25; i+=2){
   System.out.print("Floor Element of " + i +" is ");
   System.out.println(mySet.floor(i));
  }   
 }
}

Output
Elements in mySet are
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Floor Element of 1 is null
Floor Element of 3 is 2
Floor Element of 5 is 4
Floor Element of 7 is 6
Floor Element of 9 is 8
Floor Element of 11 is 10
Floor Element of 13 is 12
Floor Element of 15 is 14
Floor Element of 17 is 16
Floor Element of 19 is 18
Floor Element of 21 is 20
Floor Element of 23 is 20
Floor Element of 25 is 20

1. throws NullPointerException if the specified element is null and this set does not permit null elements

import java.util.*;

class NavigableSetFloorNullPointer{
 public static void main(String args[]){
  NavigableSet<Integer> mySet = new TreeSet<> ();
  
  for(int i=20; i >0; i-=2)
   mySet.add(i);
   
  System.out.println("Elements in mySet are");
  System.out.println(mySet+"\n");

  System.out.println("Floor Element Of null is");
  mySet.floor(null);
 }
}

Output
Elements in mySet are
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Floor Element Of null is
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1188)
        at java.util.TreeMap.getFloorEntry(TreeMap.java:422)
        at java.util.TreeMap.floorKey(TreeMap.java:725)
        at java.util.TreeSet.floor(TreeSet.java:425)
        at NavigableSetFloorNullPointer.main(NavigableSetFloorNullPointer.java:14)

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


Prevoius                                                 Next                                                 Home

No comments:

Post a Comment