Collections • A collection (sometimes called a container) is an object that groups multiple elements into a single unit. • Collections are used to store, retrieve and manipulate data, and to transmit data from one method to another. • Collections typically represent data items that form a natural group, a card hand, a mail folder, a telephone directory… 10/17/08
CS2 - Java Collection Framework
1
The Java Collections Framework • The Java collections framework is made up of a set of interfaces and classes for working with groups of objects • The Java Collections Framework provides – Interfaces: abstract data types representing collections. Implementations: concrete implementations of the collection interfaces. – Algorithms: methods that perform useful computations, like searching and sorting, on objects that implement collection interfaces. 10/17/08
CS2 - Java Collection Framework
2
The Interfaces
Note: Some of the material on these slides was taken from the Java Tutorial at http://www.java.sun.com/docs/books/tutorial
10/17/08
CS2 - Java Collection Framework
3
Collection Interfaces and Classes Collection List
Set SortedSet AbstractCollection
AbstractList
AbstractSet
AbstractSequentialList
LinkedList
ArrayList Vector
HashSet
TreeSet LinkedTreeSet
10/17/08
CS2 - Java Collection Framework
4
Map Interfaces and Classes Map
SortedMap AbstractMap
HashMap
TreeMap
LinkedHashMap 10/17/08
CS2 - Java Collection Framework
5
Sets • A group of unique items, meaning that the group contains no duplicates • Some examples – – – –
The set of uppercase letters ‘A’ through ‘Z’ The set of nonnegative integers { 0, 1, 2, … } The empty set {} The students in this class
• The basic properties of sets – Contain only one instance of each item – May be finite or infinite – Can define abstract concepts 10/17/08
CS2 - Java Collection Framework
6
Lists • Elements in a list are ordered – By insertion sequence, if nothing else – By magnitude, alphabetical order, etc.
• A list can contain duplicate entries – e.g., a list of purchased items can include the same item more than once.
10/17/08
CS2 - Java Collection Framework
7
Maps • A map is a set of pairs – each pair represents a one-directional “mapping” from one object (the key) to another (the value)
• The typical use of a Map is to provide access to values stored by key • Some examples – – – –
10/17/08
A map of student IDs to database records A dictionary (words mapped to meanings) The conversion from base 2 to base 10 Names to phone numbers CS2 - Java Collection Framework
8
Collections, Maps… What Is The Real Difference? • Collections – You can add, remove, lookup isolated items in the collection
• Maps – The collection operations are available but they work with a key-value pair instead of an isolated element
10/17/08
CS2 - Java Collection Framework
9
Another Way to Look At It • The Collection interface is a group of objects, with duplicates allowed • Set extends Collection but forbids duplicates • List extends Collection and allows duplicates and positional indexing • Map extends neither Set nor List nor Collection 10/17/08
CS2 - Java Collection Framework
10
The Collection Interface Collection
Found in the java.util package Optional methods throw UnsupportedOperationException if the implementing class does not support the operation. Bulk operations perform some operation on an entire Collection in a single shot The toArray methods allow the contents of a Collection to be translated into An array. 10/17/08
// Basic Operations size():int; isEmpty():boolean; contains(Object):boolean; add(Object):boolean; // Optional remove(Object):boolean; // Optional iterator():Iterator; // Bulk Operations containsAll(Collection):boolean; addAll(Collection):boolean; // removeAll(Collection):boolean; // retainAll(Collecton):boolean; // clear():void; //
Optional Optional Optional Optional
// Array Operations toArray():Object[]; toArray(Object[]):Object[];
CS2 - Java Collection Framework
11
Set Interface • A Set is a Collection that cannot contain duplicate elements. – Set models the mathematical set abstraction.
• The Set interface extends Collection and contains no methods other than those inherited from Collection • It adds the restriction that duplicate elements are prohibited. • Two Set objects are equal if they contain the same elements. 10/17/08
CS2 - Java Collection Framework
12
Set Bulk Operations • The bulk operations perform standard setalgebraic operations. Suppose s1 and s2 are Sets. – s1.containsAll(s2): Returns true if s2 is a subset of s1. – s1.addAll(s2): Transforms s1 into the union of s1 and s2. (The union of two sets is the set containing all the elements contained in either set.) – s1.retainAll(s2): Transforms s1 into the intersection of s1 and s2. 10/17/08
• (The intersection of two sets is the set containing only the elements that are common in both sets.) CS2 - Java Collection Framework
13
Java Lists • A List is an ordered Collection (sometimes called a sequence). • Lists may contain duplicate elements. • In addition to the operations inherited from Collection, the List interface includes operations for: – – – – 10/17/08
Positional Access Search List Iteration Range-view CS2 - Java Collection Framework
14
List Interface List // Positional Access get(int):Object; set(int,Object):Object; add(int, Object):void; remove(int index):Object; addAll(int, Collection):boolean;
// // // //
Optional Optional Optional Optional
// Search int indexOf(Object); int lastIndexOf(Object); // Iteration listIterator():ListIterator; listIterator(int):ListIterator; // Range-view List subList(int, int):List; 10/17/08
CS2 - Java Collection Framework
15
Java Maps • Accessing Map elements is different from accessing List and Set elements, so the methods are different. – Map does not inherit from Collection
• Map interface provides for storing and accessing both key and value objects
10/17/08
CS2 - Java Collection Framework
16
Map Interface Map // Basic Operations put(Object, Object):Object; get(Object):Object; remove(Object):Object; containsKey(Object):boolean; containsValue(Object):boolean; size():int; isEmpty():boolean;
EntrySet getKey():Object; getValue():Object; setValue(Object):Object;
// Bulk Operations void putAll(Map t):void; void clear():void; // Collection Views keySet():Set; values():Collection; entrySet():Set; 10/17/08
CS2 - Java Collection Framework
17
Iterator • An object that implements the Iterator interface generates a series of elements, one at a time – Successive calls to the next() method return successive elements of the series.
• The remove() method removes from the underlying Collection the last element that was returned by next(). 10/17/08
Iterator hasNext():boolean; next():Object; remove():void;
CS2 - Java Collection Framework
18
ListIterator • the ListIterator interface extends Iterator – Forward and reverse directions are possible
• ListIterator is available for Java Lists, particularly the LinkedList implementation 10/17/08
ListIterator hasNext():boolean; next():Object; hasPrevious():boolean; previous(): Object; nextIndex(): int; previousIndex(): int; remove():void; set(Object o): void; add(Object o): void;
CS2 - Java Collection Framework
19
Implementation Classes Interface Set
Implementation HashSet
List Map
TreeSet ArrayList
HashMap
Historical
LinkedList TreeMap
Vector Stack HashTable Properties
Note: When writing programs think about interfaces and not implementations. This way the program does not become dependent on any added methods in a given implementation, leaving the programmer with the freedom to change implementations.
10/17/08
CS2 - Java Collection Framework
20
In-class exercise • Create an Automobile class that you will use in collections. – Instance variables: make, model, year, hp – Instance methods: equals(), compareTo(), toString()
• Write a Java class which – Creates several Automobiles – Puts the Automobiles in an ArrayList – Iterates through the Collection of Automobiles printing information about each one. 10/17/08
CS2 - Java Collection Framework
21
Choosing an Implementation • Fast random access by key: • Access data by key with frequent need to traverse the set of keys in order: • No duplicates allowed; fast access to individual objects: • Frequent need to report sorted individual data elements: • Duplicates allowed; need to access data by position; new elements usually added to the end: • Duplicates allowed; usual need is to traverse the collection in order: 10/17/08
CS2 - Java Collection Framework
22
UniqueWords import java.io.*; import java.util.*; public class UniqueWords { public static void main( String args[] ) { // Usage check & open file if ( args.length != 1 ) { System.err.println( "Usage: java UniqueWords word-file" ); System.exit( 1 ); } StreamTokenizer in = null; try { in = new StreamTokenizer( new BufferedReader ( new FileReader( args[ 0 ] ) ) ); in.ordinaryChar( '.' ); } catch ( FileNotFoundException e ) { System.err.println( "UniqueWords: " + e.getMessage() ); System.exit( 1 ); } 10/17/08 CS2 - Java Collection Framework 23
UniqueWords try { Set set = new HashSet(); while ( ( in.nextToken() != in.TT_EOF ) ) { if ( in.ttype == in.TT_WORD ) set.add( in.sval ); } System.out.println( "There are " + set.size() + " unique words" ); System.out.println( set ); } catch ( IOException e ) { System.err.println( "UniqueWords: System.exit( 1 ); }
" + e.getMessage() );
} }
10/17/08
CS2 - Java Collection Framework
24
You Want Them Sorted? try { SortedSet set = new TreeSet(); while ( ( in.nextToken() != in.TT_EOF ) ) { if ( in.ttype == in.TT_WORD ) set.add( in.sval ); } System.out.println( "There are " + set.size() + " unique words" ); System.out.println( set ); } catch ( IOException e ) { System.err.println( "UniqueWords: System.exit( 1 ); }
" + e.getMessage() );
} }
10/17/08
CS2 - Java Collection Framework
25
Or try { Set set = new HashSet(); while ( ( in.nextToken() != in.TT_EOF ) ) { if ( in.ttype == in.TT_WORD ) set.add( in.sval ); } System.out.println( "There are " + set.size() + " unique words" ); System.out.println( new TreeSet(set) ); } catch ( IOException e ) { System.err.println( "UniqueWords: System.exit( 1 ); }
" + e.getMessage() );
} }
10/17/08
CS2 - Java Collection Framework
26
Pretty Output try { SortedSet set = new TreeSet(); while ( ( in.nextToken() != in.TT_EOF ) ) { if ( in.ttype == in.TT_WORD ) set.add( in.sval ); } System.out.println( "There are " + set.size() + " unique words" ); Iterator elements = set.iterator(); System.out.println(); while ( elements.hasNext() ) System.out.println( elements.next() ); } catch ( IOException e ) { System.err.println( "UniqueWords: System.exit( 1 ); }
" + e.getMessage() );
} }
10/17/08
CS2 - Java Collection Framework
27
CountWords try { HashMap map = new HashMap(); Integer one = new Integer( 1 ); while ( ( in.nextToken() != in.TT_EOF ) ) { if ( in.ttype == in.TT_WORD ) { Integer freq = ( Integer )map.get( in.sval ); if ( freq == null ) freq = one; else freq = new Integer( freq.intValue() + 1 ); map.put( in.sval, freq ); } }
10/17/08
CS2 - Java Collection Framework
28
CountWords System.out.println( "There are " + map.size() + " unique words" ); SortedMap sorted = new TreeMap( map ); Iterator elements = sorted.entrySet().iterator(); while ( elements.hasNext() ) { Map.Entry cur = ( Map.Entry )elements.next(); System.out.println( cur.getValue() + "\t" + cur.getKey() ); } } catch ( IOException e ) { System.err.println( "UniqueWords: System.exit( 1 ); }
10/17/08
" + e.getMessage() );
CS2 - Java Collection Framework
29
What About User Objects? • The Collections framework will work with any Java class • You need to be sure you have defined – equals() – hashCode() – compareTo()
• Don’t use mutable objects for keys in a Map 10/17/08
CS2 - Java Collection Framework
30
Interface Comparable • This ordering is referred to as the class's natural ordering, and the class's compareTo() method is referred to as its natural comparison method. • A class's natural ordering is said to be consistent with equals if, and only if, (e1.compareTo((Object)e2)==0) has the same boolean value as: e1.equals((Object)e2) – for every e1 and e2 of class C. 10/17/08
CS2 - Java Collection Framework
31
hashCode() • hashCode()returns distinct integers for distinct objects – used for determining location in a Map. – If two objects are equal according to the equals() method, then the hashCode() method on each of the two objects must produce the same integer result. – When hashCode() is invoked on the same object more than once, it must return the same integer (provided no information used in equals() comparisons has been modified). – It is not required that if two objects are unequal according to equals()that hashCode() must return distinct integer values. 10/17/08
CS2 - Java Collection Framework
32
Name import java.util.*; import java.util.*; public class Name implements Comparable { private String first; private String last; public Name( String firstName, String lastName ) { first = firstName; last = lastName; } public String getFirst() { return first; } public String getLast() { return last; }
10/17/08
CS2 - Java Collection Framework
33
Name public boolean equals( Object o ) { boolean retval = false; if (o !=null && o instanceof Name ) { Name n = ( Name )o; retval = n.getFirst().equals( first ) && n.getLast().equals( last ); } return retval; } public int hashCode() { return first.hashCode() + last.hashCode(); } public String toString() { return first + " " + last; }
10/17/08
CS2 - Java Collection Framework
34
Name public int compareTo( Object o ) throws ClassCastException { int retval; Name n = ( Name ) o; retval = last.compareTo( n.getLast() ); if ( retval == 0 ) retval = first.compareTo( n.getFirst() ); return retval; } } //Name
10/17/08
CS2 - Java Collection Framework
35
In-class exercise 2 • After creating the list of Automobiles, have your program sort them in their “natural order.” • Iterate through the sorted list and display the Automobiles in order.
10/17/08
CS2 - Java Collection Framework
36
Comparator Interface • When a collection must be sorted in a different order than its “natural order,” you can provide an object implementing the Comparator Interface to do so. – – – – 10/17/08
Sort people by age instead of name Sort cars by year instead of Make and Model Sort clients by city instead of name Sort words alphabetically regardless of case CS2 - Java Collection Framework
37
Comparator Interface • One method: compare( Object o1, Object o2 )
• Returns: negative if o1 < o2 Zero if o1 == o2 positive if o1 > o2
10/17/08
CS2 - Java Collection Framework
38
Example Comparator: Compare 2 Strings regardless of case import java.util.*; public class CaseInsensitiveComparator implements Comparator { public int compare( Object one, Object two ) { String stringOne = (String) one; String stringTwo = (String) two; // Shift both strings to lower case, and then use the // usual String instance method compareTo() return stringOne.toLowerCase().compareTo( stringTwo.toLowerCase() ); } }
10/17/08
CS2 - Java Collection Framework
39
Using a Comparator Collections.sort( myList, myComparator ); Collections.max( myCollection, myComparator ); Set myTree = new TreeSet( myComparator ); Map myMap = new TreeMap( myComparator ); import java.util.*; public class SortExample2B { public static void main( String args[] ) { List aList = new ArrayList(); for ( int i = 0; i < args.length; i++ ) { aList.add( args[ i ] ); } Collections.sort( aList , new CaseInsensitiveComparator() ); System.out.println( aList ); } } 10/17/08
CS2 - Java Collection Framework
40
In-class exercise 3 • Write a Comparator to sort Automobiles by year. • Alter your program so that your list of Automobiles is sorted by year, using your new class that implements Comparator.
10/17/08
CS2 - Java Collection Framework
41
Java Generics Type Safety for Collections The old way: List myIntList = new LinkedList(); myIntList.add(new Integer(0)); Integer x = (Integer) myIntList.iterator().next();
The new way: List
myIntList = new LinkedList(); myIntList.add(new Integer(0)); Integer x = myIntList.iterator().next();
The LinkedList myIntList now accepts only Integer objects, and returns only Integer objects (no need for casting). 10/17/08
CS2 - Java Collection Framework
42
The Comparable I/F with Generics class Automobile implements Comparable { String make, model; int year, hp; Automobile( String mk, String mdl, int yr, int power ) { make = mk; model = mdl; year = yr; hp = power; } public int compareTo( Automobile otherCar ) { if( this.make.compareTo( otherCar.make ) == 0 ) { if( this.model.compareTo( otherCar.model ) == 0 ) { return this.year - otherCar.year; } return this.model.compareTo( otherCar.model ); } return this.make.compareTo( otherCar.make ); } public boolean equals( Object other ) { Automobile otherCar = (Automobile)other; return this.make.equals( otherCar.make ) && this.model.equals( otherCar.model ) && this.year == otherCar.year; } public int hashCode() { return make.hashCode() + model.hashCode() + year; } public String toString() { return year + " " + make + " " + model; } }
43
The Comparator I/F with Generics import java.util.*; public class CompareByYear implements Comparator { public int compare( Automobile carOne, Automobile carTwo ) { return carOne.year - carTwo.year; } }
10/17/08
CS2 - Java Collection Framework
44
Using Generics import java.util.*; public class AutoCollection { public static void main( String[] args ) { Set Leno = new HashSet(); Leno.add( new Automobile( "Ford", "Thunderbird", 1988, 195 ) ); Leno.add( new Automobile( "VW", "Passat", 2001, 170 ) ); Leno.add( new Automobile( "Pontiac", "Grand Prix", 2005, 200 ) ); Iterator iter = Leno.iterator(); while( iter.hasNext() ) { System.out.println( iter.next() ); } } }
10/17/08
CS2 - Java Collection Framework
45