Taming Mustang, Part 1: Collections API
Mustang (also known as Java Standard Edition 6) has arrived. This latest Java 2 platform from Sun Microsystems is overflowing with new and enhanced APIs, including Console I/O, java.io.File’s partition-space methods, a Splash-Screen API, a System Tray API, File’s access permissions control methods, desktop integration via the Desktop API, programmatic access to network parameters, and table sorting and filtering.
I explored the first four example APIs in my "Start Saddling Up for Mustang" article for JavaWorld, and the last four example APIs in my "Mustang (Java SE 6) Gallops into Town" Informit article.
This article is the first of a three-part series that continues to tame Mustang. Part 1 focuses on enhancements made to the Collections API, where you discover new Collections interfaces and classes—and several methods that have been introduced to Collections’ utility classes.
Collections API Enhancements
The Collections API (also known as the Collections Framework) has been enhanced to facilitate bi-directional access to various kinds of collections, as evidenced by several new interfaces and classes. It has also been enhanced through several new methods that have been added to the java.util.Collections and java.util.Arrays utility classes.
New Interfaces and Classes
The Collections API introduces the following new java.util interfaces—the first interface is implemented by a retrofitted java.util.LinkedList class, the third interface is implemented by a retrofitted java.util.TreeMap class, and the fifth interface is implemented by a retrofitted java.util.TreeSet class:
- Deque describes a linear collection that supports insertion and removal at both ends. This linear collection is known as a double-ended queue—deque (pronounced "deck") for short.
- BlockingDeque is a Deque that also supports the "wait for the deque to become non-empty during element retrieval" and "wait for space to become available during element storage" blocking operations.
- NavigableMap is a java.util.SortedMap with navigation methods that report closest matches for given search targets. It may be traversed in ascending or descending key order.
- ConcurrentNavigableMap is a java.util.concurrent.ConcurrentMap that supports NavigableMap operations. These operations are also supported by sub-maps.
- NavigableSet is a java.util.SortedSet with navigation methods that report closest matches for given search targets. It may be traversed in ascending or descending order.
The Collections API also introduces the following new java.util concrete implementation classes:
- ArrayDeque offers a resizable array implementation of a Deque. There are no capacity restrictions (it grows as necessary), it prohibits null elements, and it is not thread-safe.
- ConcurrentSkipListMap offers a scalable concurrent ConcurrentNavigableMap implementation. The map is sorted according to its keys’ natural ordering, or by a java.util.Comparator passed to an appropriate constructor.
- ConcurrentSkipListSet offers a scalable concurrent NavigableSet implementation based on a ConcurrentSkipListMap. The set’s elements are kept sorted according to their natural ordering, or by a Comparator passed to an appropriate constructor.
- LinkedBlockingDeque offers a concurrent, scalable, and optionally-bounded First-In-First-Out (FIFO) blocking deque that is backed by linked nodes.
- AbstractMap.SimpleEntry offers a mutable implementation of the java.util.Map.Entry interface, which maintains a key and a value.
- AbstractMap.SimpleImmutableEntry offers an immutable implementation of Map.Entry. Unlike SimpleEntry, this class’s public V setValue(V value) method always throws UnsupportedOperationException.
For brevity, let us focus on just the NavigableSet interface. Mustang introduced this interface to overcome the limitations of its parent SortedSet interface. For example, where the parent interface lets you traverse a set in ascending order only, NavigableSet lets you traverse a set in ascending or descending order. Listing 1 accomplishes both traversals.
Listing 1 NSDemo1.java
// NSDemo1.java import java.util.*; public class NSDemo1 { public static void main (String [] args) { // Create a NavigableSet. NavigableSet<String> ns = new TreeSet<String> (); // Populate the NavigableSet. String [] planets = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" }; for (String planet: planets) ns.add (planet); // View the elements in ascending order. System.out.println ("Ascending order view"); System.out.println (); Iterator iter = ns.iterator (); while (iter.hasNext ()) System.out.println (iter.next ()); System.out.println (); // View the elements in descending order. System.out.println ("Descending order view"); System.out.println (); iter = ns.descendingIterator (); while (iter.hasNext ()) System.out.println (iter.next ()); } }
NSDemo1 introduces NavigableSet’s public Iterator<E> iterator() and public Iterator<E> descendingIterator() methods, which are used to traverse the same set in ascending and descending order (respectively). The results of these iterators can be seen in the following output:
Ascending order view Earth Jupiter Mars Mercury Neptune Saturn Uranus Venus Descending order view Venus Uranus Saturn Neptune Mercury Mars Jupiter Earth
The descendingIterator() method is equivalent to descendingSet().iterator(), where public NavigableSet<E> descendingSet() returns a reverse-order view (as a descending set) of the elements contained in this set—the descending set is backed by this set so that changes made to either set are reflected in the other set. Listing 2 demonstrates descendingSet().
Listing 2 NSDemo2.java
// NSDemo2.java import java.util.*; public class NSDemo2 { public static void main (String [] args) { // Create a NavigableSet. NavigableSet<String> ns = new TreeSet<String> (); // Populate the NavigableSet. String [] planets = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune" }; for (String planet: planets) ns.add (planet); // View the elements in ascending order. System.out.println ("Ascending order view"); System.out.println (); Iterator iter = ns.iterator (); while (iter.hasNext ()) System.out.println (iter.next ()); System.out.println (); // Exercise the ceiling/floor/higher/lower methods. exerciseCFHL (ns, "Mars"); // View the elements in descending order. System.out.println ("Descending order view"); System.out.println (); iter = ns.descendingIterator (); while (iter.hasNext ()) System.out.println (iter.next ()); System.out.println (); // Exercise the ceiling/floor/higher/lower methods. exerciseCFHL (ns.descendingSet (), "Mars"); } public static void exerciseCFHL (NavigableSet<String> ns, String planet) { // View the least element in the set greater than or equal to planet. System.out.println ("ceiling(’" + planet + "’) = " + ns.ceiling (planet)); // View the greatest element in the set less than or equal to planet. System.out.println ("floor(’" + planet + "’) = " + ns.floor (planet)); // View the least element in the set higher than planet. System.out.println ("higher(’" + planet + "’) = " + ns.higher (planet)); // View the greatest element in the set lower than planet. System.out.println ("lower(’" + planet + "’) = " + ns.lower (planet)); System.out.println (); } }
Along with descendingSet(), NSDemo2 introduces public E ceiling(E e), public E floor(E e), public E higher(E e), and public E lower(E e). These closest-match methods respectively return (in this set) the least element greater than or equal to, the greatest element less than or equal to, the least element greater than, and the greatest element less than element e. Match results appear as follows:
Ascending order view Earth Jupiter Mars Mercury Neptune Saturn Uranus Venus ceiling(’Mars’) = Mars floor(’Mars’) = Mars higher(’Mars’) = Mercury lower(’Mars’) = Jupiter Descending order view Venus Uranus Saturn Neptune Mercury Mars Jupiter Earth ceiling(’Mars’) = Mars floor(’Mars’) = Mars higher(’Mars’) = Jupiter lower(’Mars’) = Mercury
The output shows that the closest-match methods are influenced by set order. For example, Mercury comes after Mars in an ascending set, whereas Jupiter comes after Mars in a descending set. If there is no closest match (such as ceiling("Vulcan"), assuming the former ascending set), the closest-match method returns null.
The NavigableSet interface provides many interesting methods beyond its iterator, descending set, and closest-match methods. For example, E pollFirst() and E pollLast() retrieve and remove the first (lowest) and last (highest) elements from a set. Each method returns null if the set is empty. Learn more about these and other methods by checking out the Java SE 6 NavigableSet documentation.
New Utility Methods
In addition to providing various interfaces and classes that describe and implement a wide range of collections, the Collections API provides the Collections and Arrays utility classes, where each class presents a wide range of useful static (utility) methods. Mustang’s Collections class introduces two new utility methods:
- public static <T> Queue<T> asLifoQueue(Deque<T> deque) returns a view of a Deque as a Last-In-First-Out (LIFO) queue. This java.util.Queue instance behaves like a stack.
- public static <E> Set<E> newSetFromMap(Map<E, Boolean> map) returns a set that is backed by a map. The set presents the same ordering, concurrency, and performance as the backing map.
Not to be outdone, Mustang’s Arrays class introduces three new utility methods:
- public static <T> int binarySearch(T [] a, int fromIndex, int
toIndex, T key, Comparator<? super T> c) searches the fromIndex to toIndex range of pre-sorted array a for key using the Binary Search algorithm.
The same Comparator as specified via public static <T> void sort(T [] a, int fromIndex, int toIndex, Comparator<? super T> c) is passed to c—a null value uses the array’s natural ordering for comparisons.
- public static int [] copyOf(int [] original, int newLength) and nine other copyOf() methods copy the original array to a new array, truncating or padding with zeroes (if needed) so that the new array has the specified newLength.
- public static int [] copyOfRange(int [] original, int from, int to) and nine other copyOfRange() methods copy part of the original array to a new array, truncating or padding with zeroes (if needed) so that the new array has the right length.
I’ve prepared a Tokens application that demonstrates the asLifoQueue() method, along with the Deque and Queue interfaces, and the ArrayDeque class. This application twice tokenizes a string, adding each token sequence either to a FIFO deque or to a LIFO deque, and then outputs the deque’s tokens—its source code is presented in Listing 3.
Listing 3 Tokens.java
// Tokens.java import java.util.*; public class Tokens { public static void main (String [] args) { Deque<String> deque = new ArrayDeque<String> (); tokenize (deque, "The quick brown fox jumped over the lazy dog"); output ("Deque-based queue", deque); Queue<String> queue = Collections.asLifoQueue (deque); tokenize (queue, "The quick brown fox jumped over the lazy dog"); output ("Deque-view queue", queue); } static void output (String title, Queue queue) { System.out.println (title); System.out.println (); int size = queue.size (); for (int i = 0; i < size; i++) System.out.println (queue.remove ()); System.out.println (); } static void tokenize (Queue<String> queue, String s) { StringTokenizer st = new StringTokenizer (s); while (st.hasMoreTokens ()) queue.add (st.nextToken ()); } }
The first tokenize (deque, "The quick brown fox jumped over the lazy dog"); method call tokenizes "The quick brown fox jumped over the lazy dog", and then adds its tokens to the deque (which is also a queue) by calling Queue’s public boolean add(E e) method. The ArrayDeque class implements this method to add the token to the rear of the deque—FIFO order.
The second tokenize() call adds the string’s tokens to a queue by calling the same add() method. But because Collections.asLifoQueue (deque) returns an instance of an internal nested class whose add() method invokes ArrayDeque’s public void addFirst(E e) method, the token is added to the front of the deque—LIFO order.
Regardless of whether tokens are added to the rear or to the front of the deque, static void output(String title, Queue queue) invokes Queue’s public E remove() method to remove each token from the deque’s front, and then output the token—tokens output in either FIFO or LIFO order, as shown here:
Deque-based queue The quick brown fox jumped over the lazy dog Deque-view queue dog lazy the over jumped fox brown quick The