Using a Collection

Before we get into developing our own collection-based classes around the DOM, an example of using one of the predefined collections is in order. Listing 6.1 makes use of several of the collection classes and allows for manipulating a list of book titles. In the following sections, we will expand these ideas to develop our own simple collections on top of the DOM.

Note

It's really a shame that when the DOM II specification was being drafted its developers didn't spend more time examining the Java 2.0 collections interfaces. Back in Chapter 4 where we discussed the DOM II interfaces, you might remember the nodeIterator interface. The nodeIterator goes much of the way toward providing a traditional JDK 2.0 collection. With only a little more time and effort, nodeIterator and the filter interfaces could have been collections in the Java sense and would have provided interesting definitions for other languages to build on. During the remainder of this chapter we will just build them ourselves!


Code Listing 6.1. SortExample.java—Using a Simple Collection
  1: /*
  2:  * @(#)SortExample.java        1.0 2000/815
  3:  *
  4:  * Copyright (c) 1999 Macmillan USA.
  5:  * All Rights Reserved.
  6:  *
  7:  */
  8: package sams.chp6;
  9:
 10: import java.io.InputStreamReader;
 11: import java.io.BufferedReader;
 12: import java.io.IOException;
 13: import java.util.*;
 14:
 15: public class SortExample
 16: {
 17:     ArrayList bookList = new ArrayList();
 18:     public SortExample (String sTitle)
 19:     {
 20:         System.out.println("Creating array of books");
 21:         bookList.add(new Book("Better Living Thru Chemistry",
 22:                               "A. Publisher", 4.27));
 23:         bookList.add(new Book("Java 2 for C/C++ Programmers",
 24:                               "J.Wiley & Sons", 62.50));
 25:         bookList.add(new Book(
 26:                      "The Microsoft Visual J++ 1.1 Sourcebook",
 27:                       "J.Wiley & Sons", 39.95));
 28:         bookList.add(new Book("XML and Java",
 29:                       "Macmillian Computer Publishers", 49.95));
 30:         bookList.add(new Book("Inside Visual C++ 5.0",
 31:                       "Microsoft Press", 99.99));
 32:
 33:         sortList("(Default)");
 34:         boolean done = false;
 35:         InputStreamReader isr = new InputStreamReader(System.in);
 36:         BufferedReader br = new BufferedReader(isr);
 37:         while ( !done)
 38:         {
 39:             System.out.println("Sort by:");
 40:             System.out.println(" 1 for Title");
 41:             System.out.println(" 2 for Publisher");
 42:             System.out.println(" 3 for Price");
 43:             System.out.println(" 4 to add new book");
 44:             System.out.println(" 5 to exit");
 45:             System.out.println("Enter (1,2,3,4,5): ");
 46:             System.out.flush();
 47:             String command;
 48:             try
 49:             {
 50:                 command = br.readLine();
 51:                 if (command.equals("done"))
 52:                 {
 53:                     done=true;
 54:                     continue;
 55:                 }
 56:                 if (command != null && command.length() > 0)
 57:                 {
 58:                     switch (Integer.parseInt(command))
 59:                     {
 60:                      . . .
 61:                     }  // end switch
 62:                 }  // end if command
 63:             }  catch (IOException e) {  done = true;}
 64:         }  // end while not done
 65:
 66:     }
 67:
 68:     private void sortList (String sSortCriteria)
 69:     {
 70:         if (sSortCriteria == null || sSortCriteria.equals(""))
 71:             return;
 72:
 73:         Comparator c = null;
 74:         if (sSortCriteria.equals("Title"))
 75:             c = new TitleComparator();
 76:         else if (sSortCriteria.equals("Publisher"))
 77:             c = new PublisherComparator();
 78:         else if (sSortCriteria.equals("Price"))
 79:             c = new CostComparator();
 80:         if ( null == c)
 81:             Collections.sort(bookList);
 82:         else
 83:             Collections.sort(bookList,c);
 84:
 85:         displayList(bookList);
 86:     }
 87: 
 88:     private void displayList(ArrayList list)
 89:     {
 90:         Iterator it = list.iterator();
 91:         while (it.hasNext())
 92:         {
 93:             Book p = (Book) it.next();
 94:             System.out.println(p.sTitle + ", " + p.sPublisher+ ", " + p.dPrice);
 95:         } 
					96:     } 
 97:     public static void main (String args[])
 98:     {
 99:         new SortExample("Sort Example");
100:     }
101:
102:     class Book implements Comparable
103:     {
104:         String sTitle = "";
105:         String sPublisher = "";
106:         double dPrice = 0.0;
107:
108:         public Book ()
109:         {
110:             try
111:             {
112:                 InputStreamReader isr =
113:                    new InputStreamReader(System.in);
114:                    . . .
115:             }  catch (IOException e) {
116:                 sTitle = sPublisher = "";
117:                 dPrice=0;
118:                 return;
119:             }
120:         }
121:         public String toString()
122:         {
123:             String result= "Title:" + sTitle +"Publisher:"+ sPublisher + "Price:" +
 dPrice;
124:             return result;
125:         }
126:         public Book (String sTitle,
127:                      String sPublisher,
128:                      double dPrice)
129:         {
130:             this.sTitle = sTitle;
131:             this.sPublisher = sPublisher;
132:             this.dPrice = dPrice;
133:         }
134: 
135:         private Comparator defaultComparator = new TitleComparator();
136:         public int compareTo (Object o)
137:         {
138:             return (defaultComparator.compare(this, o));
139:         }
140:     }
141:
142:
143:     class TitleComparator implements Comparator
144:     {
145:         public int compare (Object book1, Object book2)
146:         {
147:             String sTitle1 = ((Book)book1).sTitle;
148:             String sTitle2 = ((Book)book2).sTitle;
149:             return (sTitle1.compareTo(sTitle2));
150:         }
151:     }
152:
153:     class PublisherComparator implements Comparator
154:     {
155:         public int compare (Object book1, Object book2)
156:         {
157:             String sPublisher1 = ((Book)book1).sPublisher;
158:             String sPublisher2 = ((Book)book2).sPublisher;
159:             return (sPublisher1.compareTo(sPublisher2));
160:         }
161:     }
162:     class CostComparator implements Comparator
163:     {
164:         public int compare (Object book1, Object book2)
165:         {
166:             double price1 = ((Book)book1).dPrice;
167:             double price2 = ((Book)book2).dPrice;
168:             if ( price1 == price2 )
169:                 return 0;
170:             else if (price1 < price2)
171:                 return -1;
172:             else
173:                 return 1;
174:         }
175:     }
176: }
177: 

Listing 6.1 implements a simple java.util.ArrayList collection. An ArrayList extends from an AbstractList, then List, and ultimately Collection and provides the basics of a growable array object. Methods exist for adding objects, clearing the array, and for the normally expected operations such as size(), isEmpty(), and so forth. SortExample.java shows a number of the most commonly used features of a collection. In fact, most developers will use precisely these operations when they develop code that uses collections.

Examining the listing line by line, we can see the more important aspects of collections in use. First, on line 13 we import the collection classes that are part of java.util. In our simple example we use ArrayList, although List would have worked as well, to manipulate instances of Book objects. Examining line 102 we see the definition of the Book inner class. Book implements the Comparable interface, which requires the method compareTo() to be defined. The important aspect of the Comparable interface is that it is used to define an ordering on books. What exactly is meant by an ordering? We won't go into the mathematical definition of an ordering, but suffice it to say that an ordering defines how we might list our books. If we were defining words in a dictionary, a natural ordering would be lexicographical order. By default, we'll order by title. Lines 135–139 define the compareTo() method, which defines how Book objects are ordered relative to one another.

Often users need to traverse a collection of objects. Two specific interfaces are supplied just for this purpose, Iterator and ListIterator. Lines 88–96 define a simple method, displayList(), which traverses our list using an Iterator. For those familiar with the Enumeration, the methods of Iterator will come as no surprise. hasNext() returns true or false depending on whether the Iteration has more elements. next() returns the next object, which we cast to type Book, and throws NoSuchElementException if no additional elements exist. One additional method that goes beyond what Enumerations provide is the remove() method. Remove removes the last item returned by the Iteration and throws UnsupportedOperationException or IllegalStateException if it fails. In addition to Iterator, we could have traversed the list using a ListIterator. ListIterator extends Iterator and so contains all its methods, but adds methods for traversing the list backward as well as forward and other methods for adding and changing the underlying collection. Developers interested in ListIterator should see the JDK documentation for a complete list of its methods. In any case, we obtain a reference to an instance of Iterator or ListIterator interfaces on a given collection via the iterator() or listIterator() methods on the collection of interest.

We've examined much of the example, but two areas have not yet been covered: adding elements and sorting. Lines 21 and 22 handle the adding of elements nicely. Sorting is another matter altogether. Collections can be manipulated using a set of polymorphic algorithms. Polymorphic is one of those 10-cent big words, but for our purposes its simple definition of "many forms" is enough. Our sortList method, lines 68–86, uses the Collections sort algorithm to sort our list using a given ordering—in this case, title, price, or publisher order. In each case an instance of a class that implements the Comparator interface is used. Comparator orders objects and requires a single method to be implemented, compare, which is much like the compareTo method defined on lines 136–139.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.244.44