Bulk OperationsSo far, most of our examples used an iterator to traverse a collection, one element at a time. However, you can often avoid iteration by using one of the bulk operations in the library. Suppose you want to find the intersection of two sets, the elements that two sets have in common. First, make a new set to hold the result. Set result = new HashSet(a); Here, you use the fact that every collection has a constructor whose parameter is another collection that holds the initialization values.
Now, use the result.retainAll(b);
It retains all elements that also happen to be in You can carry this idea further and apply a bulk operation to a view. For example, suppose you have a map that maps employee IDs to employee objects, and you have a set of the IDs of all employees that are to be terminated. Map staffMap = . . .; Set terminatedIDs = . . .; Simply form the key set and remove all IDs of terminated employees. staffMap.keySet().removeAll(terminatedIDs); Because the key set is a view into the map, the keys and associated employee names are automatically removed from the map. By using a subrange view, you can restrict bulk operations to sublists and subsets. For example, suppose you want to add the first ten elements of a list to another container. Form a sublist to pick out the first ten: relocated.addAll(staff.subList(0, 10)); The subrange can also be a target of a mutating operation. staff.subList(0, 10).clear(); Interfacing with Legacy APIs
Since large portions of the Java platform API were designed before the
collections framework was created, you occasionally need to translate
between traditional arrays and vectors and the more modern collections.
First, consider the case where you have values in an array or vector and
you want to put them into a collection. If the values are inside a
Vector values = . . .; HashSet staff = new HashSet(values);
All collection classes have a constructor that can take an arbitrary
collection object. Since the Java 2 platform, the
If you have an array, you need to turn it into a collection. The
String[] values = . . .;
HashSet staff = new HashSet(
Arrays.asList(values));
Conversely, if you need to call a method that requires a vector, you can construct a vector from any collection: Vector values = new Vector(staff);
Obtaining an array is a bit trickier. Of course, you can use the Object[] values = staff.toArray(); But the result is an array of objects. Even if you know that your collection contained objects of a specific type, you cannot use a cast: String[] values = (String[])staff.toArray(); // Error!
The array returned by the
String[] values = (
String[])staff.toArray(
new String[0]);
NOTE: You may wonder why you don't simply pass a Class object (such as
java.util.Collection
Generic collection interfaces have a great advantage--you only need to implement your algorithms once. For example, consider a simple algorithm to compute the maximum element in a collection. Traditionally, programmers would implement such an algorithm as a loop. Here is how you find the largest element of an array. if (a.length == 0) throw new NoSuchElementException(); Comparable largest = a[0]; for (int i = 1; i < a.length; i++) if (largest.compareto(a[i]) < 0) largest = a[i]; Of course, to find the maximum of a vector, the code would be slightly different.
What about a linked list? You don't have random access in a linked list. But you can use an iterator.
These loops are tedious to write, and they are just a bit error-prone. Is there an off-by-one error? Do the loops work correctly for empty containers? For containers with only one element? You don't want to test and debug this code every time, but you also don't want to implement a whole slew of methods such as these: Object max(Comparable[] a) Object max(Vector v) Object max(LinkedList l)
That's where the collection interfaces come in. Think of the minimal
collection interface that you need to efficiently carry out the algorithm.
Random access with get and set comes higher in the food chain than simple
iteration. As you have seen in the computation of the maximum element in a
linked list, random access is not required for this task. Computing the
maximum can be done simply by iterating through the elements. Therefore,
you can implement the max method to take any object that implements the
Now you can compute the maximum of a linked list, a vector, or an array, with a single method.
That's a powerful concept. In fact, the standard C++ library has dozens of useful algorithms, each of which operates on a generic collection. The Java library is not quite so rich, but it does contain the basics: sorting, binary search, and some utility algorithms. Sorting and ShufflingComputer old-timers will sometimes reminisce about how they had to use punched cards and how they actually had to program sorting algorithms by hand. Nowadays, of course, sorting algorithms are part of the standard library for most programming languages, and the Java programming language is no exception.
The sort method in the List staff = new LinkedList(); // fill collection . . .; Collections.sort(staff);
This method assumes that the list elements implement the
If you want to sort a list in descending order, then use the static
convenience method
Collections.sort(
staff, Collections.reverseOrder())
sorts the elements in the list staff in reverse order, according to the ordering given by the compareTo method of the element type. You may wonder how the sort method sorts a list. Typically, when you look at a sorting algorithm in a book on algorithms, it is presented for arrays and uses random element access. But random access in a list can be inefficient. You can actually sort lists efficiently by using a form of merge sort (see, for example, Algorithms in C++, Parts 1-4, by Robert Sedgwick [Addison-Wesley 1998, p. 366-369]). However, the implementation in the Java programming language does not do that. It simply dumps all elements into an array, sorts the array, using a different variant of merge sort, and then copies the sorted sequence back into the list. The merge sort algorithm used in the collections library is a bit slower than quick sort, the traditional choice for a general-purpose sorting algorithm. However, it has one major advantage: it is stable, that is, it doesn't switch equal elements. Why do you care about the order of equal elements? Here is a common scenario. Suppose you have an employee list that you already sorted by name. Now you sort by salary. What happens to employees with equal salary? With a stable sort, the ordering by name is preserved. In other words, the outcome is a list that is sorted first by salary, then by name. Because collections need not implement all of their optional methods, all methods that receive collection parameters need to describe when it is safe to pass a collection to an algorithm. For example, you clearly cannot pass an unmodifiableList list to the sort algorithm. What kind of list can you pass? According to the documentation, the list must be modifiable but need not be resizable. These terms are defined as follows:
The ArrayList cards = . . .; Collections.shuffle(cards); The current implementation of the shuffle algorithm requires random access to the list elements, so it won't work too well with a large linked list. The program in Example 2-5 fills an array list with 49 Integer objects containing the numbers 1 through 49. It then randomly shuffles the list and selects the first 6 values from the shuffled list. Finally, it sorts the selected values and prints them out. Example 25: ShuffleTest.java
java.util.Collections
Binary SearchTo find an object in an array, you normally need to visit all elements until you find a match. However, if the array is sorted, then you can look at the middle element and check if it is larger than the element that you are trying to find. If so, you keep looking in the first half of the array; otherwise, you look in the second half. That cuts the problem in half. You keep going in the same way. For example, if the array has 1024 elements, you will locate the match (or confirm that there is none) after 10 steps, whereas a linear search would have taken you an average of 512 steps if the element is present and 1024 steps to confirm that it is not.
The
i = Collections.binarySearch(
c, element);
i = Collections.binarySearch(
c, element, comparator);
If the return value of the binarySearch method is ³ 0, it denotes the index
of the matching object. That is, insertionPoint = -i - 1;
It isn't simply if (i < 0) c.add(-i - 1, element); adds the element in the correct place. To be worthwhile, binary search requires random access. If you have to iterate one by one through half of a linked list to find the middle element, you have lost all advantage of the binary search. Therefore, the binarySearch algorithm reverts to a linear search if you give it a linked list.
NOTE: Unfortunately, since there is no separate interface for an ordered collection with efficient random access, the binarySearch method employs
a very crude device to find out whether to carry out a binary or a linear
search. It checks whether the list parameter implements the
AbstractSequentialList class. If it does, then the parameter is certainly a
linked list, because the abstract sequential list is a skeleton implementation
of a linked list. In all other cases, the binarySearch algorithm makes the
assumption that the collection supports efficient random access and proceeds
with a binary search.
java.util.Collections
The
The following API notes describe the simple algorithms in the java.util.Collections
If you write your own algorithm (or in fact, any method that has a collection
as a parameter), you should work with interfaces, not concrete implementations,
whenever possible. For example, suppose you want to fill a
However, you now constrained the caller of your method--the caller must supply the choices in a vector. If the choices happened to be in another container, they need to first be repackaged. It is much better to accept a more general collection.
You should ask yourself what is the most general collection interface that
can do the job. In this case, you just need to visit all elements, a
capability of the basic
Now, anyone can call this method with a vector or even with an array,
wrapped with the
NOTE: If it is such a good idea to use collection interfaces as method
parameters, why doesn't the Java library follow this rule more often? For
example, the JComboBox(Object[] items) JComboBox(Vector items) The reason is simply timing. The Swing library was created before the collections library. You should expect future APIs to rely more heavily on the collections library. In particular, vectors should be on their way out because of the synchronization overhead. If you write a method that returns a collection, you don't have to change the return type to a collection interface. The user of your method might in fact have a slight preference to receive the most concrete class possible. However, for your own convenience, you may want to return an interface instead of a class, because you can then change your mind and reimplement the method later with a different collection.
For example, let's write a method
Or, you could change the return type to List. List getAllItems(JComboBox comboBox)
Then, you are free to change the implementation later. For example, you may
decide that you don't want to copy the elements of the combo box but simply
provide a view into them. You achieve this by returning an anonymous subclass
of
Of course, this is an advanced technique. If you employ it, be careful to document exactly which optional operations are supported. In this case, you must advise the caller that the returned object is an unmodifiable list. Legacy Collections
In this section, we discuss the collection classes that existed in the Java
programming language since the beginning: the The Hashtable Class
The classic
Enumerations
The legacy collections use the
For example, the elements method of the
You will occasionally encounter a legacy method that expects an enumeration
parameter. The
NOTE: In C++, it is quite common to use iterators as parameters. Fortunately, in programming for the Java platform, very few programmers use this idiom. It is much smarter to pass around the collection than to pass an iterator. The collection object is more useful. The recipients can always obtain the
iterator from it when they need it, plus they have all the collection methods
at their disposal. However, you will find enumerations in some legacy code
since they were the only available mechanism for generic collections until
the collections framework appeared in the Java 2 platform.
java.util.Enumeration
java.util.Hashtable
java.util.Vector
Property Sets
A
The Java platform class that implements a property set is called Property sets are useful in specifying configuration options for programs. The environment variables in Unix and DOS are good examples. On a PC, your AUTOEXEC.BAT file might contain the settings: SET PROMPT=$p$g SET TEMP=C:\Windows\Temp SET CLASSPATH=c:\jdk\lib;. Here is how you would model those settings as a property set in the Java programming language.
Use the store method to save this list of properties to a file. Here, we just print the property set to the standard output. The second argument is a comment that is included in the file.
settings.store(System.out,
"Environment settings");
The sample table gives the following output.
Here's another example of the ubiquity of the
Here is an example of what you would see when you run the program. You can
see all the values stored in this
NOTE: For security reasons, applets can only access a small subset of these properties.
| ||||||||||||||||||||||||||
|
| ||||||||||||