Home > Articles > Programming > Java

Taming Mustang, Part 1: Collections API

📄 Contents

  1. Collections API Enhancements
  2. What's Next?
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. Jeff Friesen, a longtime Java expert who has written several articles and books on Java technology, presents 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.
Like this article? We recommend

Like this article? We recommend

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

 

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020