Monday, 21 April 2014

NavigableSet : lower : Get greates lower element of this element

E lower(E e)
Returns the greatest element in this set strictly less than the given element.

import java.util.*;

class NavigableSetLower{
 public static void main(String args[]){
  NavigableSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements too mySet */
  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<22; i+=2){
   System.out.print("Greates lower Element of " + i +" is ");
   System.out.println(mySet.lower(i));
  }
 }
}

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

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

1. throws NullPointerException if the specified element is null and this set does not permit null elements
import java.util.*;

class NavigableSetLowerNullPointer{
 public static void main(String args[]){
  NavigableSet<Integer> mySet = new TreeSet<> ();
  
  /* Add Elements too mySet */
  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("Greates Lower Element for null is");
  mySet.lower(null);
 }
}

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

Greates Lower Element for null is
Exception in thread "main" java.lang.NullPointerException
        at java.util.TreeMap.compare(TreeMap.java:1188)
        at java.util.TreeMap.getLowerEntry(TreeMap.java:487)
        at java.util.TreeMap.lowerKey(TreeMap.java:703)
        at java.util.TreeSet.lower(TreeSet.java:414)
        at NavigableSetLowerNullPointer.main(NavigableSetLowerNullPointer.java:16)
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