NavigableSet API is included in the ocpjp 6 certification exam. This article explains few important methods with simple example program.NavigableSet is the subinterface of SortedSet. This interface defines methods for finding the element in a list. For example lower() method used for finding the element which is less than the given value. Look into the following example:
package javabeat.net; import java.util.ArrayList; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; public class NavigableSetExample1 { public static void main(String args[]){ List<Integer> list = new ArrayList<Integer>(); list.add(3); list.add(4); list.add(1); list.add(8); list.add(7); list.add(10); NavigableSet navigableSet = new TreeSet(list); System.out.println(navigableSet.lower(8)); System.out.println(navigableSet.higher(8)); } }
In the above code, NavigableSet.lower() method is used for reteriving the value which is less than ‘8’ in the list. Same way NavigableSet.higher() is used for reteriving the value greater than ‘8’ in the list. The output for the above program would be:
7 10
Other than finding less than or greater than values, NavigableSet provides few more useful methods to print the values in the desired order. Look into the following code snippet:
package javabeat.net; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NavigableSet; import java.util.TreeSet; public class NavigableSetExample2 { public static void main(String args[]){ List<Integer> list = new ArrayList<Integer>(); list.add(4); list.add(6); list.add(9); list.add(5); NavigableSet navigableSet = new TreeSet(list); Iterator<Integer> iterator = (Iterator)navigableSet.descendingIterator(); while (iterator.hasNext()){ Integer value = iterator.next(); System.out.println(value); } } }
Above code demonstrates how to print the values in decending order using the NaviogableSet API
4) What will be the output of the following program?
package navset; import java.util.TreeSet; public class Ques02 { public static void main(String[] args) { MyNavigableSet objects = new MyNavigableSet(); objects.add(new Object()); System.out.println(objects); } } class MyNavigableSet extends TreeSet<String>{ public boolean add(Object value){ return super.add(value); } }
- The program will compile and run fine to print the contents of the set.
- The program will raise a run-time exception telling that it is not possible to add objects of type ‘java.lang.Object’ in place of ‘java.lang.String’.
- The program will raise a compile-time error.
Answer
4) c.
A compile-time error telling that a name-clash has happened for the overridden method taking Object as argument.