Previous
Index

Next


Chapter 9) The java.util package

Objective 1, The collection classes/interfaces

Make appropriate selection of collection classes/interfaces to suit specified behavior requirements.

Note on this Objective

Although it does not mention it specifically, this objective involves one of the new objectives for the Java2 version of the exam, a knowledge of the collection classes. The exam questions on these new collections are fairly basic, requiring a knowledge of where and how you might use them, rather than a detailed knowledge of the fields and methods.

The old collections

The Java 2 API includes new interfaces and classes to enhance the collections available. Earlier versions of Java included

vector

hashtable

array

BitSet

Of these, only array was included in the objectives for the 1.1 certification exam. One of the noticeable omissions from Java 1.1 was support for sorting, a very common requirement in any programming situation,

The new collections

At the root of the Collection API is the Collection interface. This gives you a series of common methods that all collection classes will have. You would probably never create your own class that implements Collection as Java supplies a series of sub-interfaces and classes that uses the Collection interface.

The Java2 API includes the following new collection interfaces

Sets

Maps

Classes that implement the Collection interface store objects as elements rather than primitives. This approach has the drawback that creating objects has a performance overhead and the elements must be cast back from Object to the appropriate type before being used. It also means that the collections do not check that the elements are all of the same type, as an object can be just about anything.

A Set

A Set is a collection interface that cannot contain duplicate elements. It thus matches nicely onto concepts such as a record set returned from a relational database. Part of the magic of the Set interface is in the add method.

add(Object o)

Any object passed to the add method must implement the equals method so the value can be compared with existing objects in the class. If the set already contains this object the call to add leaves the set unchanged and returns false. The idea of returning false when attempting to add an element seems more like the approach used in C/C++ than Java. Most similar Java methods would seem to throw an Exception in this type of situation.

A List

A list is a sorted collection interface that can contain duplicates

Some important methods are

add

remove

clear

The JDK documentation gives the example of using List to manage an actual GUI list control containing a list of the names of the Planets.

A Map

Map is an interface, classes that implement it cannot contain duplicate keys, and it is similar to a hashtable.

Why use Collections instead of arrays?.

The big advantage of the collections over arrays is that the collections are growable, you do not have to assign the size at creation time. The drawback of collections is that they only store objects and not primitives and this comes with an inevitable performance overhead. Arrays do not directly support sorting, but this can be overcome by using the static methods of the Collections. Here is an example.

import java.util.*;

public class Sort{
    public static void main(String argv[]){
    Sort s = new Sort();
    }

Sort(){
    String s[] = new String[4];
    s[0]="z";
    s[1]="b";
    s[2]="c";
    s[3]="a";
    Arrays.sort(s);
    for(int i=0;i< s.length;i++)
    System.out.println(s[i]);
    }
}

    

Set and Map collections ensure uniqueness, List Collections do not ensure uniqueness but are sorted (ordered)

Using Vectors

The following example illustrates how you can add objects of different classes to a Vector. This contrasts with arrays where every element must be of the same type. The code then walks through each object printing to the standard output. This implicitly access the toString() method of each object.

import java.awt.*;
import java.util.*;
public class Vec{
public static void main(String argv[]){
    Vec v = new Vec();
    v.amethod();
    }//End of main

public void amethod(){
        Vector mv = new Vector();
        //Note how a vector can store objects 
        //of different types
        mv.addElement("Hello");
        mv.addElement(Color.red);
        mv.addElement(new Integer(99));
        //This would cause an error
        //As a vector will not store primitives
        //mv.addElement(99)
        //Walk through each element of the vector
        for(int i=0; i< mv.size(); i++){
            System.out.println(mv.elementAt(i));
            }
   }//End of amethod
}



Prior to Java2 the Vector class was the main way of creating a re-sizable data structure. Elements can be removed from the Vector class with the remove method.

Using Hashtables

Hashtables are a little like the Visual Basic concept of a Collection used with a key. It acts like a Vector, except that instead of referring to elements by number, you refer to them by key. The hash part of the name refers to a math term dealing with creating indexes. A hashtable can offer the benefit over a Vector of faster look ups.

BitSet

A BitSet as its name implies, stores a sequence of Bits. Don't be misled by the "set" part of its name its not a set in the mathematical or database sense, nor is it related to the Sets available in Java2. It is more appropriate to think of it as a bit vector. A BitSet may useful for the efficient storage of bits where the bits are used to represent true/false values. The alternative of using some sort of collection containing Boolean values can be less efficient.

According to Bruce Eckel in "Thinking in Java"

It’s efficient only from the standpoint of size; if you’re looking for efficient access, it is slightly slower than using an array of some native type.

The BitSet is somewhat of a novelty class which you may never have a need for. I suspect that it might be handy for the purposes of cryptography or the processing of images. Please let me know if you come across a question relating to it in the Java2 exam.

Questions

Question 1)

Which of the following are collection classes?

1) Collection
2) Iterator
3) HashSet
4) Vector


Question 2)

Which of the following are true about the Collection interface?

1) The Vector class has been modified to implement Collection
2) The Collection interface offers individual methods and Bulk methods such as addAll
3) The Collection interface is backwardly compatible and all methods are available within the JDK 1.1 classes
4) The collection classes make it unnecessary to use arrays


Question 3)

Which of the following are true?

1) The Set interface is designed to ensure that implementing classes have unique members
2) Classes that implement the List interface may not contain duplicate elements
3) The Set interface is designed for storing records returned from a database query
4) The Map Interface is not part of the Collection Framework


Question 4)

Which of the following are true?

1) The elements of a Collection class can be ordered by using the sort method of the Collection interface
2) You can create an ordered Collection by instantiating a class that implements the List interface
3) The Collection interface sort method takes parameters of A or D to change the sort order, Ascending/Descending
4) The elements of a Collection class can be ordered by using the order method of the Collection interface


Question 5)


You wish to store a small amount of data and make it available for rapid access. You do not have a need for the data to be sorted, uniqueness is not an issue and the data will remain fairly static Which data structure might be most suitable for this requirement?

1) TreeSet
2) HashMap
3) LinkedList
4) an array


Question 6)

Which of the following are Collection classes?

1) ListBag
2) HashMap
3) Vector
4) SetList


Question 7)

How can you remove an element from a Vector?

1) delete method
2) cancel method
3) clear method
4) remove method

Answers

Answer 1)

3) HashSet
4) Vector

The other two are Interfaces not classes


Answer 2)

1) The Vector class has been modified to implement Collection
2) The Collection interface offers individual methods and Bulk methods such as addAll

The Collection classes are new to the JDK1.2 (Java2) release. With the exception of the classes that have been retrofitted such as Vector and BitSet the, if you run any of the Collections through an older JDK you will get a compile time error.


Answer 3)

1) The Set interface is designed to ensure that implementing classes have unique members

Elements of a class that implements the List interface may contain duplicate elements. Although a class that implements the Set interface might be used for storing records returned from a database query, it is not designed particularly for that purpose.


Answer 4)

2) You can create an ordered Collection by instantiating a class that implements the List interface


Answer 5)


4) an array

For such a simple requirement an ordinary array will probably be the best solution


Answer 6)

2) HashMap
3) Vector

With the release of JDK 1.2 (Java2) the Vector class was "retro-fitted" to become a member of the Collection Framework


Answer 7)

4) remove method


Other sources on this topic

The Sun Tutorial
http://java.sun.com/docs/books/tutorial/collections/index.html

Jyothi Krishnan on this topic at
http://www.geocities.com/SiliconValley/Network/3693/obj_sec10.html#obj30

JDK 1.4 Tutorial from Manning
http://www.manning.com/travis/chap08.pdf






Previous
Index

Next