SDSU CS 596 Java Programming
Fall Semester, 1998
JDK 1.2 Collections
To Lecture Notes Index
© 1998, All Rights Reserved, SDSU & Roger Whitney
San Diego State University -- This page last updated 20-Oct-98

Contents of Doc 13, JDK 1.2 Collections


References


JDK 1.2 on-line documentation at: http://www.eli.sdsu.edu/doc/jdk1.2/docs/guide/collections/index.html

JDK 1.2 source code

Listen Here!S-oct12 1min Doc 13, JDK 1.2 Collections Slide # 2

JDK 1.2 Collection/Map Classes


A collection object manages a group (collection) of elements

JDK 1.2 has major improvements in the collection/map classes over JDK 1.1

Improved Performance
More Collection Classes
More Functionality
Better Integration of Classes


Things to Cover

Using the JDK 1.2 Collection/Map classes with JDK 1.1
Name Changes and Replaced Classes
Collection/Map Types
Collection/Map Type Methods
Collection/Map Implementations
Iterators verses Enumerations
Sorting & Comparing
Immutable (read-only) Collections
Synchronized Collections
Collection/Map Utilities

Listen Here!S-oct12 1min Doc 13, JDK 1.2 Collections Slide # 3
Name Changes and Replacement Classes

In the original JDK a number of short sighted and/or poor choices were made. In JDK 1.2, an attempt is made to correct theses choices. Rather than modify some of the classes involved new (replacement) classes are added to the JDK. The following table lists the old classes/interfaces and their replacements. If you are going to work in a JDK 1.2 only environment use the replacements.

Old Classes
Replacement
Enumeration
Iterator, ListIterator
Hashtable
HashMap
Vector
ArrayList

Some of the method names used in the original JDK are rather wordy and troublesome to type. The names in the replacement classes tend to be shorter. The following table shows some examples.

Old Names
New Names
hasMoreElements()
hasNext()
nextElement()
next()
addElement()
add()
setElementAt()
set()
elementAt()
get()


Doc 13, JDK 1.2 Collections Slide # 4

Using 1.2 Collections/Maps with JDK 1.1


Sun has released the collection classes for JDK 1.1. This package can be found at ftp://ftp.javasoft.com/pub/beans/1.1collections.zip. In JDK 1.2, the collection packages are in the package "java.util". For security reasons in applets, the collection classes can not be the package "java.util". They are in the package "com.sun.java.util.collections". Thus, to use these classes in a 1.1 JVM you must include the collections.zip or collections.jar in your classpath and use the longer package name. On rohan you need to add /opt/local/lib/java/other/1.1collections/lib/collections.jar to your path. You can not get the full functionality of the Map classes. You must use the Comparator interface with Maps. Using the comparable interface will not work unless you are very clever.

In JDK 1.2

import java.util.ArrayList;
public class Test {
   public static void main(String args[])  {
      ArrayList a = new ArrayList();
      a.add( "a");
      a.add( "b");
      System.out.println( a );
   }
}

In JDK 1.1
import com.sun.java.util.collections.ArrayList;
public class Test {
   public static void main(String args[])  {
      ArrayList a = new ArrayList();
      a.add( "a");
      a.add( "b");
      System.out.println( a );
   }
}

Listen Here!Q-oct8 8mins, Q-oct8 2mins, S-oct12 8mins Doc 13, JDK 1.2 Collections Slide # 5

Collection/Map Road Map




Abstract classes used for implementation purposes are not shown. Hidden and anonymous classes are not shown.

Doc 13, JDK 1.2 Collections Slide # 6
Collection/Map Types

The following types of collections/Maps are defined in JDK 1.2 using interfaces

Collection
A group of Objects
Parent interface of all other collection types

Set
No duplicate elements permitted
Order (if any) is established at creation time.

List (Ordered Collection or sequence)
Duplicates are generally permitted
Caller has control over the position of each element

Map
A mapping from keys to values
Each key can map to at most one value.

SortedSet -
A Set whose elements are automatically sorted

SortedMap -
A Map sorted by keys


Doc 13, JDK 1.2 Collections Slide # 7
Collection/Map Implementations

HashSet
A Set backed by a hash table

TreeSet
A balanced binary tree implementation of the SortedSet interface

ArrayList
A resizable-array implementation of the List interface
Replaces Vector

LinkedList
A doubly-linked List

HashMap
A hash table implementation of the Map interface
Replaces Hashtable

TreeMap
A balanced binary tree implementation of the SortedMap interface

Vector
A List with additional legacy methods

Hashtable
A Map with additional legacy methods

WeakHashMap
A special-purpose implementation of the Map interface that stores only weak references


Listen Here!Q-oct8 2mins, S-oct12 2mins Doc 13, JDK 1.2 Collections Slide # 8
Methods of the Collections/MapsCollection

add(Object o)
Iterator iterator()
boolean addAll(Collection c)
boolean remove(Object o)
void clear()
boolean removeAll(Collection c)
boolean contains(Object o)
boolean retainAll(Collection c)
boolean containsAll(Collection c)
int size()
boolean equals(Object o)
Object[] toArray()
int hashCode()
Object[] toArray(Object[] a)
boolean isEmpty()


List
void add(int index, Object element)
Iterator iterator()
boolean add(Object o)
int lastIndexOf(Object o)
boolean addAll(Collection c)
ListIterator listIterator()
boolean addAll(int index, Collection c)
ListIterator listIterator(int index)
void clear()
Object remove(int index)
boolean contains(Object o)
boolean remove(Object o)
boolean containsAll(Collection c)
boolean removeAll(Collection c)
boolean equals(Object o)
boolean retainAll(Collection c)
Object get(int index)
Object set( int index, Object element)
int hashCode()
int size()
int indexOf(Object o)
List subList(int fromIndex, int toIndex)
boolean isEmpty()
Object[] toArray()

Object[] toArray(Object[] a)


Doc 13, JDK 1.2 Collections Slide # 9
Set
boolean add(Object o)
boolean isEmpty()
boolean addAll(Collection c)
Iterator iterator()
void clear()
boolean remove(Object o)
boolean contains(Object o)
boolean removeAll(Collection c)
boolean containsAll(Collection c)
boolean retainAll(Collection c)
boolean equals(Object o)
int size()
int hashCode()
Object[] toArray()
Object[] toArray(Object[] a)


SortedSet
Comparator comparator()
Object last()
first()
SortedSet subSet(Object from, Object to)
SortedSet headSet(Object to)
SortedSet tailSet(Object fromElement)


Map
void clear()
boolean isEmpty()
boolean containsKey(Object key)
Set keySet()
boolean containsValue(Object value)
Object put(Object key, Object value)
Set entrySet()
void putAll(Map t)
boolean equals(Object o)
Object remove(Object key)
Object get(Object key)
int size()
int hashCode()
Collection values()


SortedMap
Comparator comparator()
Object lastKey()
Object firstKey()
SortedMap subMap(Object from, Object to)
SortedMap headMap(Object toKey)
SortedMap tailMap(Object fromKey)


Listen Here!Q-oct8 2mins, S-oct12 45secs Doc 13, JDK 1.2 Collections Slide # 10

Lists

A List is an ordered collection or sequence. There are three implementations of this interface: ArrayList, Vector, and LinkedList.

import java.util.*;

public class TestArrayList {
   public static void main(String args[]) {
      ArrayList aList = new ArrayList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      aList.add( "hat");
      
      System.out.println( "Index of cat: " + aList.indexOf( "cat" ) );
      
      aList.set( 1, "katze" );
      aList.remove( "in" );
      System.out.println( "Changed aList: " + aList );
      
      List shortList = aList.subList( 1, 3 );
      System.out.println( "Sublist: " + shortList );
      }
   }
Output
Index of cat: 1
Changed aList: [a, katze, hat]
Sublist: [katze, hat]

Listen Here!Q-oct8 57secs, S-oct12 1min Doc 13, JDK 1.2 Collections Slide # 11
LinkedList
A simple example using a LinkedList object. Notice it uses the same methods as the ArrayList.
import java.util.*;

public class TestLinkedList {
   public static void main(String args[])  {
      LinkedList aList = new LinkedList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      aList.add( "hat");
      
      System.out.println( "Index of cat: " + aList.indexOf( "cat" ) );
      
      aList.set( 1, "katze" );
      aList.remove( "in" );
      System.out.println( "Changed aList: " + aList );
      
      List shortList = aList.subList( 1, 3 );
      System.out.println( "Sublist: " + shortList );
   }
}
Output
Index of cat: 1
Changed aList: [a, katze, hat]
Sublist: [katze, hat]

Listen Here!Q-oct8 5mins, S-oct12 3mins Doc 13, JDK 1.2 Collections Slide # 12
Why Interfaces?
LinkedLists, ArrayLists, and Vectors support the same interface: List. A variable of type List can reference a linkedList, arrayList, or a vector. Using the type List provides programs flexibility to change the implementations. If you start with an ArrayList and later decide to use a linked list, you can change the one line of code that creates the object.
import java.util.*;
public class ThreeInOne {
   public static void main(String args[]) {
      LinkedList aLinkedList = new LinkedList();
      cat( aLinkedList );
      System.out.println( "Linked List: " + aLinkedList );
      
      ArrayList aArrayList = new ArrayList();
      cat( aArrayList );
      System.out.println( "Array List: " + aArrayList );
      
      Vector aVector = new Vector();
      cat( aVector );
      System.out.println( "Vector: " + aVector );
   }
   public static void cat( List aList) {
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      aList.add( "hat");
      aList.set( 1, "katze" );
   }
}
Output
Linked List: [a, katze, in, hat]
Array List: [a, katze, in, hat]
Vector: [a, katze, in, hat]

Doc 13, JDK 1.2 Collections Slide # 13

Sets

Sets do not store duplicates of items. Adding duplicates has no affect. In HashSets, the items are stored in a hash table. In TreeSets, items are stored in a balanced binary search tree (red-black tree) in order. A TreeSet object must be able to order the elements added to it. See Sorting on a later slide.

import java.util.*;
public class TestSets {
   public static void main(String args[])  {
      String[] title = { "the", "cat", "in", "the", "hat", "in" };
      HashSet unique = new HashSet();
      
      for ( int k = 0; k < title.length; k++ )
         unique.add( title[k] );
      
      System.out.println( "Hash order: " + unique );
      TreeSet orderedUnique = new TreeSet();
      
      for ( int k = 0; k < title.length; k++ )
         orderedUnique.add( title[k] );
      
      System.out.println( "Sorted order: " + orderedUnique );
   }
}
Output
Hash order: [cat, the, hat, in]
Sorted order: [cat, hat, in, the]

Doc 13, JDK 1.2 Collections Slide # 14

Maps

Maps store key-value pairs. In HashMaps, the key-value pairs are stored in a hash table. In TreeMaps, key-value pairs are stored in a balanced binary search tree (red-black tree). A TreeMap object must be able to order the elements added to it. See Sorting on a later slide.

import java.util.*;
public class TestMaps {
   public static void main(String args[]) {
      HashMap englishToGerman = new HashMap();
      englishToGerman.put( "cat", "Katze" );
      englishToGerman.put( "dog", "Hund" );
      englishToGerman.put( "bird", "Vogel" );
      System.out.println( englishToGerman );
      TreeMap ordered = new TreeMap();
      ordered.put( "cat", "Katze" );
      ordered.put( "dog", "Hund" );
      ordered.put( "bird", "Vogel" );
      System.out.println("Sorted order: " + ordered );
   }
}
Output
Hash order: {cat=Katze, dog=Hund, bird=Vogel}
Sorted order: {bird=Vogel, cat=Katze, dog=Hund}

Listen Here!Q-oct8 7mins, S-oct12 2mins Doc 13, JDK 1.2 Collections Slide # 15

Enumeration Verses Iterators


Enumeration
Iterator
ListIterator
hasMoreElements()
hasNext()
hasNext()
nextElement()
next()
next()

remove()
remove()


nextIndex()


hasPrevious()


previous()


previousIndex()


add()


set()


Iterators go through elements of a collection.

Iterator and ListIterator are fail-fast

If the underlying collection is changed (elements added or removed) by means other than the iterator, then the next time the iterator is accessed it will throw a java.util.ConcurrentModificationException


Doc 13, JDK 1.2 Collections Slide # 16
ListIterator Methods

void add(Object o)
Inserts the specified element into the List (optional).

boolean hasNext()
Returns true if this ListIterator has more elements when traversing the List in the forward direction.

boolean hasPrevious()
Returns true if this ListIterator has more elements when traversing the List in the reverse direction.

Object next()
Returns the next element in the List.

int nextIndex()
Returns the index of the element that would be returned by a subsequent call to next.

Object previous()
Returns the previous element in the List.

int previousIndex()
Returns the index of the element that would be returned by a subsequent call to previous.

void remove()
Removes from the List the last element that was returned by next or previous (optional).

void set(Object o)
Replaces the last element returned by next or previous with the specified element (optional operation).


Listen Here!S-oct12 2mins Doc 13, JDK 1.2 Collections Slide # 17
ListIterator Example

import java.util.*;
public class TestIterator {
   public static void main(String args[])  {
      List aList = new ArrayList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "hat");
      
      ListIterator myList = aList.listIterator();
      
      while ( myList.hasNext() ) {
         Object listItem = myList.next();
         if ( listItem.equals( "cat" ) ) {
            myList.set( "katze" );
            System.out.println( "Changed item at index: " + 
               myList.previousIndex() );
            break;
         }
      }
      myList.add( "in" );
      System.out.println( "Changed aList: " + aList );
   }
}
Output
Changed item at index: 1
Changed aList: [a, katze, in, hat]

Listen Here!S-oct14 5mins Doc 13, JDK 1.2 Collections Slide # 18

Converting

Arrays to Lists


One can make a list that is backed by an array of objects. This means when you access or modify the list, the array is being accesses or modified. When you have a list backed by an array you can change elements of the list (array), but you can not change the size of the list (array) by adding or removing elements. A list can not be backed by an array of base types.

import java.util.*;
public class ArrayToList {
   public static void main(String args[]) {
      String[] arrayString = { "a", "cat", "in", "the", "hat" };
      
      List backByArray = Arrays.asList( arrayString );
      
      System.out.println( backByArray.get( 1 ));
      System.out.println( backByArray.indexOf( "cat" ));
      
      backByArray.set( 1, "katze" );
      System.out.println( arrayString[ 1] );
      
      ListIterator onArray = backByArray.listIterator();
      
      backByArray.add( "is back" );
   }
}
Output
cat
1
katze
java.lang.UnsupportedOperationException
   at java.util.AbstractList.add(AbstractList.java:133)
   at java.util.AbstractList.add(AbstractList.java:78)
   at ArrayToList.main(ArrayToList.java)

Listen Here!S-oct14 9mins Doc 13, JDK 1.2 Collections Slide # 19
Converting

Collections to Arrays


All collection objects can create an array containing elements in the collection. You can either use the method toArray() or toArray( Type[ ] x). The first, toArray(), one creates an array of type Object, copies the elements in the collection to the array, then returns the array. The returned array can not be cast any other array type. The second, toArray( Type[ ] x), operates differently. If x.length >= container size, it copies the elements into x and returns it. If x.length > container size, then x[container size] is set to null. If x.length < container size then a new array is allocated of the same type as x, same size as the container.
import java.util.*;

public class CollectionToArray {
   public static void main(String args[])  {
      List aList = new ArrayList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      
      Object[] objectArray = aList.toArray(); // correct
      Object[] objectArray =(String[]) aList.toArray(); // Runtime error
      // toArray() actual returns an Object[]
      String[] stringList = (String[]) aList.toArray( new String[0] );
      // the above creates a new String array
      String[] fasterCopy = 
         (String[]) aList.toArray( new String[aList.size()] );
      // Given the correct size array means toArray does not have to 
      // create a new array.
    }
}

Listen Here!Q-oct8 2mins, S-oct14 3mins, S-oct14 9mins, Q-oct15 1min Doc 13, JDK 1.2 Collections Slide # 20

Read-only (Unmodifiable) Collections/Maps


We can create read-only collections/Maps, which are backed by other collections. This is done with the unmodifiableCollection, unmodifiableList, unmodifiableMap, unmodifiableSet, unmodifiableSortedMap, and unmodifiableSortedSet methods of the java.util.Collections class.

import java.util.*;
public class ReadOnly {
   public static void main(String args[])  {
      List aList = new ArrayList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      
      List readOnlyAList = Collections.unmodifiableList( aList );
      
      System.out.println( readOnlyAList.get( 1) );
      
      readOnlyAList.set( 1, "katze" ); // runtime error
   }
}
Output
cat
java.lang.UnsupportedOperationException
   at java.util.Collections$UnmodifiableList.set(Collections.java:625)
   at ReadOnly.main(ReadOnly.java)

Listen Here!S-oct14 2mins, Q-oct15 56secs Doc 13, JDK 1.2 Collections Slide # 21

Optional Methods


When we create a read-only collection (or list, map, etc) we can not use any method that changes an element in the collection. Although we have a collection type (and the add() method is defined in that type) we can not use add() on a read-only collection. Such a method is called an optional method. If you try to use an optional method on a collection that does not support the optional method, a runtime exception (java.lang.UnsupportedOperationException) is thrown. The following tables contain the optional methods for the collection types. SortedSet and SortedMap do not declare any new optional methods. They do inherit the optional methods from their parent interfaces.

Collection
List
add(Object o)
void add(int index, Object element)
boolean addAll(Collection c)
boolean add(Object o)
void clear()
boolean addAll(Collection c)
boolean remove(Object o)
boolean addAll(int index, Collection c)
boolean removeAll(Collection c)
void clear()
boolean retainAll(Collection c)
Object remove(int index)

boolean remove(Object o)

boolean removeAll(Collection c)

boolean retainAll(Collection c)

Object set( int index, Object element)


Set
Map
boolean add(Object o)
void clear()
boolean addAll(Collection c)
Object put(Object key, Object value)
void clear()
void putAll(Map t)
boolean remove(Object o)
Object remove(Object key)
boolean removeAll(Collection c)

boolean retainAll(Collection c)



Listen Here!S-oct14 3mins, Q-oct15 7mins Doc 13, JDK 1.2 Collections Slide # 22

Thread-safe (Synchronized) Collections/Maps


Java has threads, which allow concurrent processing in a single program. If your program uses threads, different parts of your code could access a single collection at the same time. This can cause problems if one part of the code is writing a new value to the collection when another part of the code is trying to read that value. A synchronized collection only allows one concurrent access to the collection at a time. Accessing elements in a synchronized collection takes longer than accessing elements in a non-synchronized collection. The new collection classes in JDK 1.2 are not synchronized. To get a synchronized collection backed by a normal collection, use the synchronizedCollection, synchronizedList, synchronizedMap, synchronizedSet, synchronizedSortedMap, and synchronizedSortedSet methods of the java.util.Collections class. Note that underlying collection is still not synchronized. Thus, it can be accesses concurrently and independently of the synchronized version. In addition, any iterator from the synchronized is not synchronized. The collections from JDK 1.1 (Vector and Hashtable) are thread safe.

import java.util.*;
public class ThreadSafeCollections {
   public static void main(String args[]) {
      List aList = new ArrayList();
      aList.add( "a");
      aList.add( "cat");
      aList.add( "in");
      
      List threadSafeList = Collections.synchronizedList( aList );
      
      ListIterator notThreadSafe = threadSafeList.listIterator();
   }
}

Listen Here!S-oct12 2mins, Q-oct15 1min Doc 13, JDK 1.2 Collections Slide # 23

Sorting & Comparing

Comparing

In order to sort a list of object, one needs to compare two objects to determine which object is smaller (larger). There are two basic approaches to doing such comparisons. Both approaches have their advantages. In the first approach, an object compares itself to other objects. This approach only requires one class. It also tends to require fewer method calls to make the comparison. The second approach uses a special comparator object to compare pairs of objects. This allows the same type of objects to be compared using different criteria in the same program. JDK 1.2 supports both approaches. You can use both methods on the same object.

Sorting

There are several ways to sort collections in JDK 1.2

java.util.Collections.sort() will sort any list (Vector, ArrayList, LinkedList)

java.util.Arrays.sort() will sort any array

java.util.TreeSet automatically sorts its elements

java.util.TreeMap automatically sorts its keys

Any collection object can be added to an empty list object and then sorted

Any collection object can be added to an empty TreeSet object

Listen Here!S-oct12 53secs, Q-oct15 1min Doc 13, JDK 1.2 Collections Slide # 24

Comparable


If you want your object to take responsibility for comparing itself with other object in JDK 1.2's sorting algorithms, its class must implement the java.lang.Comparable interface. When using an object that implements Comparable Collections.sort(List) and Arrays.sort(array ) use a fast quicksort to sort the elements of the list or array.

Methods in Interface
int compareTo(Object other)
Compares this Object with the specified Object for order.
Return
a negative int if current object is less than other,
0 (zero) if current object is equal to other
a positive int if current object greater than other

The following must be true:

sgn(x.compareTo(y)) == -sgn(y.compareTo(x)) for all x and y

x.compareTo(y) must throw an exception iff y.compareTo(x) throws an exception

(x.compareTo(y)>0 && y.compareTo(z)>0) implies x.compareTo(z)>0.

x.equals(y) implies that x.compareTo(y)==0

x.compareTo(y)==0 implies that sgn(x.compareTo(z)) == sgn(y.compareTo(z)), for all z.

Listen Here!S-oct12 3mins, S-oct12 4mins, Q-oct15 5mins Doc 13, JDK 1.2 Collections Slide # 25
Comparable Example

class Student implements Comparable {
   private String name;
   private int id;
   
   public Student( String newName, int id ) {
      name = newName;
      this.id = id;
      }
   
   public String toString() {
      return name + ":" + id;
      }
   public int compareTo( Object other ) {
      Student otherStudent = (Student) other;
      return name.compareTo( otherStudent.name );
      }
   }

Listen Here!S-oct12 2mins, Q-oct15 4mins Doc 13, JDK 1.2 Collections Slide # 26
//Comparable Example Continued

import java.util.*;
public class TestComparable {
   public static void main(String args[])  {
      Student[] cs596 = { new Student( "Li",  1 ), 
                                 new Student( "Swen", 2 ),
                                  new Student( "Chan", 3 ) };
      //Sorting an array
      Arrays.sort( cs596 );
      for ( int k = 0; k < cs596.length; k++ )
         System.out.print( cs596[k].toString() + ", " );
      System.out.println( );
      
      List cs596List = new ArrayList( );
      cs596List.add( new Student( "Li", 1) );
      cs596List.add( new Student( "Swen", 2 ) );
      cs596List.add( new Student( "Chan", 3 ) );
      System.out.println( "Unsorted list " + cs596List );
      
      //Sorting a collection
      Collections.sort( cs596List );
      System.out.println( "Sorted list " + cs596List );
      // TreeSets are always sorted
      TreeSet cs596Set = new TreeSet( );
      cs596Set.add( new Student( "Li", 1) );
      cs596Set.add( new Student( "Swen", 2 ) );
      cs596Set.add( new Student( "Chan", 3 ) );
      System.out.println( "Sorted Set " + cs596Set );
      }
   }

Doc 13, JDK 1.2 Collections Slide # 27
//Comparable Example ContinuedOutput

Chan:3, Li:1, Swen:2, 
Unsorted list [Li:1, Swen:2, Chan:3]
Sorted list [Chan:3, Li:1, Swen:2]
Sorted Set [Chan:3, Li:1, Swen:2]

Listen Here!S-oct12 3mins, Q-oct15 3mins Doc 13, JDK 1.2 Collections Slide # 28

Comparator

If you want same type of objects to be compared using different criteria in the same program, then you need to implement separate classes that implement Comparator interface for the types. When using Comparator Collections.sort(List, Comparator) and Arrays.sort( array, Comparator ) use mergesort, which is stable, to sort the elements of the list or array.

Methods in Interface
int compare(Object o1, Object o2)
Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second
boolean equals(Object obj)
Indicates whether some other object is "equal to" this Comparator.

The implementor must ensure that:

sgn(compare(x, y)) == -sgn(compare(y, x)) for all x and y

compare(x, y) must throw an exception if and only if compare(y, x) throws an exception.)

((compare(x, y)>0) && (compare(y, z)>0)) implies compare(x, z)>0.

x.equals(y) || (x==null && y==null) implies that compare(x, y)==0.

compare(x, y)==0 implies that sgn(compare(x, z))==sgn(compare(y, z)) for all z.

Listen Here!S-oct12 2mins, Q-oct15 31secs Doc 13, JDK 1.2 Collections Slide # 29
Comparator Example

import java.util. Comparator;
class Student  {
   String name;
   int id;
   
   public Student( String newName, int id ) {
      name = newName;
      this.id = id;
      }
   
   public String toString() {
      return name + ":" + id;
      }
   }
final class StudentNameComparator implements Comparator {
   
   public int compare( Object leftOp, Object rightOp ) {
      String leftName = ((Student) leftOp).name;
      String rightName = ((Student) rightOp).name;
      return leftName.compareTo( rightName );
   }
   
   public boolean equals( Object comparator ) {
      return comparator instanceof StudentNameComparator;
   }
}

Listen Here!S-oct12 4mins Doc 13, JDK 1.2 Collections Slide # 30
//Comparator Example Continued

final class StudentIdComparator implements Comparator {
   static final int LESS_THAN = -1;
   static final int GREATER_THAN = 1;
   static final int EQUAL = 0;
   
   public int compare( Object leftOp, Object rightOp ) {
      long leftId = ((Student) leftOp).id;
      long rightId = ((Student) rightOp).id;
      if ( leftId < rightId )   
         return LESS_THAN;
      else if ( leftId > rightId )
         return GREATER_THAN;
      else
         return EQUAL;
   }
   
   public boolean equals( Object comparator ) {
      return comparator instanceof StudentIdComparator;
   }
}

Listen Here!S-oct12 4mins, Q-oct15 2mins Doc 13, JDK 1.2 Collections Slide # 31
//Comparator Example Continued
import java.util.*;
public class Test 
   {
   public static void main(String args[]) 
      {
      Student[] cs596 = { new Student( "Li", 1 ), new Student( "Swen", 2 ), 
                                 new Student( "Chan", 3 ) };
      //Sort the array
      Arrays.sort( cs596, new StudentNameComparator() );
      for ( int k = 0; k < cs596.length; k++ )
         System.out.print( cs596[k].toString() + ", " );
      System.out.println( );
      
      List cs596List = new ArrayList( );
      cs596List.add( new Student( "Li", 1 ) );
      cs596List.add( new Student( "Swen", 2 ) );
      cs596List.add( new Student( "Chan", 3 ) );
      System.out.println( "Unsorted list " + cs596List );
      //Sort the list
      Collections.sort( cs596List,  new StudentNameComparator() );
      System.out.println( "Sorted list " + cs596List );
      //TreeSets are aways sorted
      TreeSet cs596Set = new TreeSet(  new StudentNameComparator() );
      cs596Set.add( new Student( "Li", 1 ) );
      cs596Set.add( new Student( "Swen", 2 ) );
      cs596Set.add( new Student( "Chan", 3 ) );
      System.out.println( "Sorted Set " + cs596Set );
      }
   }

Doc 13, JDK 1.2 Collections Slide # 32
//Comparator Example ContinuedOutput
Chan:3, Li:1, Swen:2, 
Unsorted list [Li:1, Swen:2, Chan:3]
Sorted list [Chan:3, Li:1, Swen:2]
Sorted Set [Chan:3, Li:1, Swen:2]

Listen Here!S-oct12 6mins Doc 13, JDK 1.2 Collections Slide # 33
Sorting With Different Keys
import java.util.*;
public class MultipleSorts {
   public static void main(String args[]) {
      List cs596List = new ArrayList( );
      cs596List.add( new Student( "Li", 1 ) );
      cs596List.add( new Student( "Swen", 2 ) );
      cs596List.add( new Student( "Chan", 3 ) );
      
      Collections.sort( cs596List,  new StudentNameComparator() );
      System.out.println( "Name Sorted list " + cs596List );
      Collections.sort( cs596List,  new StudentIdComparator() );
      System.out.println( "Id Sorted list " + cs596List );
      TreeSet cs596Set = new TreeSet( new StudentNameComparator());
      cs596Set.addAll( cs596List );
      System.out.println( "Name Sorted Set " + cs596Set );
      TreeSet cs596IdSet = new TreeSet( new StudentIdComparator() );
      cs596IdSet.addAll( cs596List );
      System.out.println( "Id Sorted Set " + cs596IdSet );
   }
}
Output
Name Sorted list [Chan:1, Li:2, Swen:1]
Id Sorted list [Chan:1, Swen:1, Li:2]
Name Sorted Set [Chan:1, Li:2, Swen:1]
Id Sorted Set [Chan:1, Li:2]

Doc 13, JDK 1.2 Collections Slide # 34

Utility Classes

JDK 1.2 has two classes that contain useful utility methods: java.util.Arrays and java.util.Collections. We have already seen some of these methods. A list of the methods in these classes follows.

Arrays


<Type> = Object, byte, short, int, long, float, double, char, or boolean

static List asList(Object[] a)
Returns a List backed by the specified array.

static int binarySearch(<Type>[] a, <Type> key)
Searches the array of base for the specified value
static int binarySearch(Object[] a, Object key, Comparator c)
Searches the array for the specified Object

static boolean equals(<Type>[] a, <Type>[] a2), etc.
Returns true if the corresponding elements in the two arrays are equal

static void fill(<Type>[] a, <Type> value)
Assigns the value to each element of the array.

static void fill(<Type> [] a, int fromIndex, int toIndex, type value)
Assigns the value to the array elements in given range
static void sort(<Type>[] a)
Sorts the array into ascending order.
static void sort(Object[] a, Comparator c)
Sorts the array according to the order induced by the specified Comparator.


Doc 13, JDK 1.2 Collections Slide # 35

Collections


static int binarySearch(List list, Object key, Comparator c)
static int binarySearch(List list, Object key)
static void copy(List dest, List src)

static Enumeration enumeration(Collection c)
Returns an Enumeration over the Collection.

static void fill(List list, Object o)
static Object max(Collection coll, Comparator comp)
static Object max(Collection coll)
static Object min(Collection coll, Comparator comp)
static Object min(Collection coll)
static List nCopies(int n, Object o)
Returns an immutable List consisting of n copies of the specified Object.

static void reverse(List l)
static Comparator reverseOrder()
Returns a Comparator that imposes the reverse of the natural ordering on a collection of Comparable objects.

static void shuffle(List list, Random rnd)
static void shuffle(List list)
static Set singleton(Object o)
Returns an immutable Set containing only the given Object.

static void sort(List list, Comparator c)
static void sort(List list)

static Collection synchronizedCollection(Collection c)
Returns a synchronized (thread-safe) Collection backed by the Collection.

static Collection unmodifiableCollection(Collection c)
Returns an unmodifiable view of the Collection.


Copyright © 1998 SDSU & Roger Whitney, 5500 Campanile Drive, San Diego, CA 92182-7700 USA.
All rights reserved.

visitors since 07-Oct-98