You are on page 1of 43

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 Vinay Nayudu - 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 Vinay Nayudu - 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 Vinay Nayudu - Java Collection Framework 3


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 Vinay Nayudu - Java Collection Framework 4
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 Vinay Nayudu - Java Collection Framework 5


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
– 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

10/17/08 Vinay Nayudu - Java Collection Framework 6


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 Vinay Nayudu - Java Collection Framework 7


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 Vinay Nayudu - Java Collection Framework 8
The Collection Interface
Found in the java.util Collection
package
// Basic Operations
size():int;
Optional methods throw isEmpty():boolean;
contains(Object):boolean;
UnsupportedOperationException
add(Object):boolean; // Optional
if the implementing class does remove(Object):boolean; // Optional
not support the operation. iterator():Iterator;

// Bulk Operations
Bulk operations perform containsAll(Collection):boolean;
some operation on an entire addAll(Collection):boolean; // Optional
Collection in a single shot removeAll(Collection):boolean; // Optional
retainAll(Collecton):boolean; // Optional
clear():void; // Optional
The toArray methods allow the contents
of a Collection to be translated into // Array Operations
An array. toArray():Object[];
toArray(Object[]):Object[];

10/17/08 Vinay Nayudu - Java Collection Framework 9


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 Vinay Nayudu - Java Collection Framework 10
Set Bulk Operations
• The bulk operations perform standard set-
algebraic 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.
• (The intersection of two sets is the set containing only the
elements that are common in both sets.)
10/17/08 Vinay Nayudu - Java Collection Framework 11
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:
– Positional Access
– Search
– List Iteration
– Range-view
10/17/08 Vinay Nayudu - Java Collection Framework 12
List Interface
List
// Positional Access
get(int):Object;
set(int,Object):Object; // Optional
add(int, Object):void; // Optional
remove(int index):Object; // Optional
addAll(int, Collection):boolean; // Optional

// Search
int indexOf(Object);
int lastIndexOf(Object);

// Iteration
listIterator():ListIterator;
listIterator(int):ListIterator;

// Range-view List
subList(int, int):List;

10/17/08 Vinay Nayudu - Java Collection Framework 13


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 Vinay Nayudu - Java Collection Framework 14


Map Interface
Map
// Basic Operations
put(Object, Object):Object;
get(Object):Object;
remove(Object):Object; EntrySet
containsKey(Object):boolean;
containsValue(Object):boolean; getKey():Object;
size():int; getValue():Object;
isEmpty():boolean; setValue(Object):Object;

// Bulk Operations
void putAll(Map t):void;
void clear():void;

// Collection Views
keySet():Set;
values():Collection;
entrySet():Set;

10/17/08 Vinay Nayudu - Java Collection Framework 15


Iterator
• An object that implements
the Iterator interface
generates a series of
elements, one at a time
– Successive calls to the Iterator
next() method return
hasNext():boolean;
successive elements of the next():Object;
series. remove():void;
• The remove() method
removes from the
underlying Collection
the last element that was
returned by next().

10/17/08 Vinay Nayudu - Java Collection Framework 16


ListIterator
• the ListIterator
interface extends
Iterator ListIterator
– Forward and reverse hasNext():boolean;
directions are possible next():Object;

• ListIterator is hasPrevious():boolean;
previous(): Object;
available for Java
nextIndex(): int;
Lists, particularly the previousIndex(): int;
LinkedList remove():void;
implementation set(Object o): void;
add(Object o): void;

10/17/08 Vinay Nayudu - Java Collection Framework 17


Implementation Classes
Interface Implementation Historical

Set HashSet TreeSet


List ArrayList LinkedList Vector
Stack
Map HashMap TreeMap 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 Vinay Nayudu - Java Collection Framework 18


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 Vinay Nayudu - Java Collection Framework 19
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 Vinay Nayudu - Java Collection Framework 20
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: " + e.getMessage() );
System.exit( 1 );
}
}
}

10/17/08 Vinay Nayudu - Java Collection Framework 21


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: " + e.getMessage() );
System.exit( 1 );
}
}
}

10/17/08 Vinay Nayudu - Java Collection Framework 22


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: " + e.getMessage() );
System.exit( 1 );
}
}
}

10/17/08 Vinay Nayudu - Java Collection Framework 23


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: " + e.getMessage() );
System.exit( 1 );
}
}
}
10/17/08 Vinay Nayudu - Java Collection Framework 24
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 Vinay Nayudu - Java Collection Framework 25


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: " + e.getMessage() );
System.exit( 1 );
}

10/17/08 Vinay Nayudu - Java Collection Framework 26


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 Vinay Nayudu - Java Collection Framework 27


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 Vinay Nayudu - Java Collection Framework 28
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 Vinay Nayudu - Java Collection Framework 29
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 Vinay Nayudu - Java Collection Framework 30


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 Vinay Nayudu - Java Collection Framework 31


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 Vinay Nayudu - Java Collection Framework 32


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 Vinay Nayudu - Java Collection Framework 33
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 Vinay Nayudu - Java Collection Framework 34


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.
– 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
10/17/08 Vinay Nayudu - Java Collection Framework 35
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 Vinay Nayudu - Java Collection Framework 36


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 Vinay Nayudu - Java Collection Framework 37


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 Vinay Nayudu - Java Collection Framework 38
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 Vinay Nayudu - Java Collection Framework 39


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<Integer> myIntList = new LinkedList<Integer>();
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 Vinay Nayudu - Java Collection Framework 40


The Comparable I/F with Generics
class Automobile implements Comparable<Automobile> {
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;
}
10/17/08
} Vinay Nayudu - Java Collection Framework 41
The Comparator I/F with Generics

import java.util.*;
public class CompareByYear implements Comparator<Automobile> {
public int compare( Automobile carOne, Automobile carTwo ) {
return carOne.year - carTwo.year;
}
}

10/17/08 Vinay Nayudu - Java Collection Framework 42


Using Generics
import java.util.*;
public class AutoCollection {

public static void main( String[] args ) {


Set<Automobile> Leno = new HashSet<Automobile>();

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 Vinay Nayudu - Java Collection Framework 43

You might also like