Java Reference
In-Depth Information
(Algorithm 4.2). Essentially the algorithm is based on the manipulation of
sets of items and sets of features.
Decision point
How do we represent the sets manipulated by the algorithm?
The simplest choice would be to use arrays that contain the elements of
the set; in this case we would have to implement all the operations for
manipulating such arrays. An alternative would be to use the standard col-
lection classes of Java (Sidebar 4.3). We choose the latter option because it
makes use of already defined operations and lets us focus on the algorithm.
Sidebar 4.3 Arrays vs collections
Collections were introduced in version 1.2 of Java. The main collection interface
is Collection . It is a container of elements that can be added to or removed from the
collection. Elements can be iterated on by means of an Iterator object. When com-
pared with an array, a collection does not exhibit a specific implementation, its
elements are not ordered, and it does not have a fixed size.
Another important difference between collections and arrays is that the former
treat their elements as Object , while the latter can have different types of elements.
The fact that collections deal with Object has two main consequences:
they cannot contain primitive type (e.g. int );
a cast is necessary when accessing their elements.
Since primitive types are not allowed, wrapper classes (e.g. Integer ) should be
used instead. Using casts brings a minor decrease in readability. We can compare
arrays and collections looking at how simple operations can be performed.
Iterator it # items.iterator();
while (it.hasNext()){
String item # (String);
// do something with the item
Using an array the same iteration code can be written as follows:
for ( int i # 0; i < items.length; !! i){
String item # items[i];
// do something with the item
The two variations of iteration are almost equally complex. The main weakness
of the former is the necessity of using casts to adapt the Object , manipulated by the
collections, and the effective classes manipulated by the program. Manipulating
Object instead of specific classes, gives great flexibility, because it is possible to
write algorithms that are independent of details.
Up to now we have looked at the advantages of using the elements of a collec-
tion; collections provide several advantages also in populating the set. When using
Search WWH ::

Custom Search