The IMaps Class
Having defined the
SortedMap<K,V> interface,
and anticipating our definition of an
IMapBST<K,V> class,
we define a second static factory method that
accepts a comparator as its argument
and returns an empty binary search tree.
// The IMaps class defines static methods for the IMap<K,V> type.
// In particular, it defines static factory methods for creating
// empty maps of the IMap<K,V> type.
import java.util.Iterator;
import java.util.Comparator;
class IMaps {
private static IMap theEmptyIMap = new IMapList();
// static factory methods for creating an empty IMap<K,V>
@SuppressWarnings("unchecked")
public static <K,V> IMap<K,V> empty () {
return (IMap<K,V>) theEmptyIMap;
}
@SuppressWarnings("unchecked")
public static <K,V> SortedIMap<K,V> empty (Comparator<? super K> c) {
return IMapBST.empty(c);
}
// main method for testing
public static void main (String[] args) {
IMapTests.main (args);
}
}
The highlighted expression calls a static factory method of the
IMapBST class, which we have yet to define.
It is not unusual for one static factory method to call another.
In this example, the IMaps class has to know about
the IMapList and IMapBST classes.
It doesn't have to know about any other classes that might be
used by the IMapBST.empty method.
How to Suppress Warning Messages
Java compilers ordinarily generate code that checks casts at run time. For historical reasons, Java compilers are unable to generate code to check casts that involve type parameters.
Java compilers emit messages that warn programmers when a cast will not be checked at run time. Those warning messages are annoying and relatively unhelpful because they are informing programmers of a defect in the design of the Java language and its implementations rather than a defect in the program being compiled.
It is therefore considered good practice to use the
@SuppressWarnings("unchecked")
annotation to suppress warning messages caused by this defect of the Java language and its implementations. It is sometimes possible to eliminate the warnings by rewriting the code, but that is not always possible.