|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
Page 3 of 5
The following code segment demonstrates how to perform many Collection operations on HashSet, a basic collection that implements the Set interface. A HashSet is simply a set that doesn't allow duplicate elements and doesn't order or position its elements. The code shows how you
create a basic collection and add, remove, and test for elements. Because Vector now supports the Collection interface, you can also execute this code on a vector, which you can test by changing the HashSet declaration and constructor to a Vector.
import java.util.collections.*;
public class CollectionTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection Test" );
// Create a collection
HashSet collection = new HashSet();
// Adding
String dog1 = "Max", dog2 = "Bailey", dog3 = "Harriet";
collection.add( dog1 );
collection.add( dog2 );
collection.add( dog3 );
// Sizing
System.out.println( "Collection created" +
", size=" + collection.size() +
", isEmpty=" + collection.isEmpty() );
// Containment
System.out.println( "Collection contains " + dog3 +
": " + collection.contains( dog3 ) );
// Iteration. Iterator supports hasNext, next, remove
System.out.println( "Collection iteration (unsorted):" );
Iterator iterator = collection.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );
// Removing
collection.remove( dog1 );
collection.clear();
}
}
Let's now build on our basic knowledge of collections and look at other interfaces and implementations in the Java Collections Framework.
We have exercised the Collection interface on a concrete collection, the HashSet. Let's now look at the complete set of concrete collection implementations provided in the Java Collections framework. (See
the Resources section for a link to Sun's annotated outline of the Java Collections framework.)
| Implementations | ||||||
|---|---|---|---|---|---|---|
| Hash Table | Resizable Array | Balanced Tree (Sorted) | Linked List | Legacy | ||
| Interfaces | Set | HashSet | * | TreeSet | * | * |
| List | * | ArrayList | * | LinkedList | Vector | |
| Map | HashMap | * | TreeMap | * | Hashtable | |
Implementations marked with an asterix (*) make no sense or provide no compelling reason to implement. For instance, providing
a List interface to a Hash Table makes no sense because there is no notion of order in a Hash Table. Similarly, there is no Map interface for a Linked List because a list has no notion of table lookup.
Let's now exercise the List interface by operating on concrete implementations that implement the List interface, the ArrayList, and the LinkedList. The code below is similar to the previous example, but it performs many List operations.
import java.util.collections.*;
public class ListTest {
// Statics
public static void main( String [] args ) {
System.out.println( "List Test" );
// Create a collection
ArrayList list = new ArrayList();
// Adding
String [] toys = { "Shoe", "Ball", "Frisbee" };
list.addAll( Arrays.toList( toys ) );
// Sizing
System.out.println( "List created" +
", size=" + list.size() +
", isEmpty=" + list.isEmpty() );
// Iteration using indexes.
System.out.println( "List iteration (unsorted):" );
for ( int i = 0; i < list.size(); i++ )
System.out.println( " " + list.get( i ) );
// Reverse Iteration using ListIterator
System.out.println( "List iteration (reverse):" );
ListIterator iterator = list.listIterator( list.size() );
while ( iterator.hasPrevious() )
System.out.println( " " + iterator.previous() );
// Removing
list.remove( 0 );
list.clear();
}
}
As with the first example, it's simple to swap out one implementation for another. You can use a LinkedList instead of an ArrayList simply by changing the line with the ArrayList constructor. Similarly, you can use a Vector, which now supports the List interface.
When deciding between these two implementations, you should consider whether the list is volatile (grows and shrinks often)
and whether access is random or ordered. My own tests have shown that the ArrayList generally outperforms the LinkedList and the new Vector.
Notice how we add elements to the list: we use the addAll method and the static method Arrays.toList. This static method is one of the most useful utility methods in the Collections framework because it allows any array to
be viewed as a List. Now an array may be used anywhere a Collection is needed.
Notice that I iterate through the list via an indexed accessor, get, and the ListIterator class. In addition to reverse iteration, the ListIterator class allows you to add, remove, and set any element in the list at the point addressed by the ListIterator. This approach is quite useful for filtering or updating a list on an element-by-element basis.
The last basic interface in the Java Collections Framework is the Map. This interface is implemented with two new concrete implementations, the TreeMap and the HashMap. The TreeMap is a balanced tree implementation that sorts elements by the key.
Let's illustrate the use of the Map interface with a simple example that shows how to add, query, and clear a collection. This example, which uses the HashMap class, is not much different from how we used the Hashtable prior to the debut of the Collections framework. Now, with the update of Hashtable to support the Map interface, you can swap out the line that instantiates the HashMap and replace it with an instantiation of the Hashtable.
import com.sun.java.util.collections.*;
public class HashMapTest {
// Statics
public static void main( String [] args ) {
System.out.println( "Collection HashMap Test" );
HashMap collection1 = new HashMap();
// Test the Collection interface
System.out.println( "Collection 1 created, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );
// Adding
collection1.put( new String( "Harriet" ), new String( "Bone" ) );
collection1.put( new String( "Bailey" ), new String( "Big Chair" ) );
collection1.put( new String( "Max" ), new String( "Tennis Ball" ) );
System.out.println( "Collection 1 populated, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );
// Test Containment/Access
String key = new String( "Harriet" );
if ( collection1.containsKey( key ) )
System.out.println( "Collection 1 access, key=" + key + ", value=" +
(String) collection1.get( key ) );
// Test iteration of keys and values
Set keys = collection1.keySet();
System.out.println( "Collection 1 iteration (unsorted), collection contains keys:" );
Iterator iterator = keys.iterator();
while ( iterator.hasNext() )
System.out.println( " " + iterator.next() );
collection1.clear();
System.out.println( "Collection 1 cleared, size=" + collection1.size() +
", isEmpty=" + collection1.isEmpty() );
}
}
We've covered most of the interfaces and implementations in the Java Collections framework, and we're ready to check out some of the additional capabilities Collections offers us.