The Java Collections Framework: Interfaces
The Java Collections Framework: Interfaces
Definition
Set of interfaces, abstract and concrete classes that define common
abstract data types in Java
e.g. list, stack, queue, set, map
Implementation
Extensive use of generic types, hash codes (Object.hashCode()) , and
Comparable interface (compareTo(), e.g. for sorting)
Collection Interface
Defines common operations for sets and lists (unordered ops.)
Maps
Represented by separate interfaces from list/set
(due to key/value relationship vs. a group of elements)
- 14 -
Note: Some of the material on these slides was taken from the Java Tutorial at http://www.java.sun.com/docs/books/tutorial
- 15 -
- 16 -
Implementation Classes
(slide derived from: Carl Reynolds)
Interface
Set
Implementation
HashSet
List
Map
TreeSet
ArrayList
HashMap
LinkedHashSet
LinkedList
TreeMap
LinkedHashMap
Note: When writing programs use the interfaces rather than the implementation classes
where you can: this makes it easier to change implementations of an ADT.
- 17 -
LinkedHashMap, LinkedHashSet
Provide support for arranging set elements or (key,value) pairs by
order of insertion by adding a linked list within the hash table
elements
TreeMap,TreeSet
Use binary search tree implementations to order set elements by
value, or (key,value) pairs by key value
- 18 -
- 19 -
- 20 -
HashSet
(Example: TestHashSet.java, Liang)
Methods:
Except for constructors, defined methods identical to Collection
Element Storage:
Unordered, but stored in a hash table according to their hash codes
**All elements are unique
Do not expect to see elements in the order you add them when you output
them using toString().
Hash Codes
Most classes in Java API override the hashCode() method in the Object
class
Need to be defined to properly disperse set elements in storage (i.e.
throughout locations of the hash table)
For two equivalent objects, hash codes must be the same
- 21 -
LinkedHashSet
(example: TestLinkedHashSet.java)
Methods
Again, same as Collection Interface except for
constructors
Addition to HashSet
Elements in hash table contain an extra field defining
order in which elements are added (as a linked list)
List maintained by the class
Hash Codes
Notes from previous slide still apply (e.g. equivalent
objects, equivalent hash codes)
- 22 -
Implementation
A binary search tree, such that either:
1. Objects (elements) implement the Comparable interface (compareTo() )
(natural order of objects in a class), or
2. TreeSet is constructed using an object implementing the Comparator
interface (compare()) to determine the ordering (permits comparing
objects of the same or different classes, create different orderings)
One of these will determine the ordering of elements.
Notes
Iterator Interface
Purpose
Provides uniform way to traverse sets and lists
Instance of Iterator given by iterator() method in Collection
Operations
Similar behaviour to operations used in Scanner to
obtain a sequence of tokens
Check if all elements have been visited (hasNext())
Get next element in order imposed by the iterator
(next())
remove() the last element returned by next()
- 24 -
List Interface
(modified slide from Carl Reynolds)
List<E>
// Positional Access
get(int):E;
set(int,E):E;
add(int, E):void;
remove(int index):E;
addAll(int, Collection):boolean;
// Search
int indexOf(E);
int lastIndexOf(E);
// Iteration
listIterator():ListIterator<E>;
listIterator(int):ListIterator<E>;
// Range-view List
subList(int, int):List<E>;
- 25 -
ListIterator
the ListIterator
interface extends
Iterator
Forward and reverse
directions are possible
ListIterator is
available for Java Lists,
such as the
LinkedList
implementation
ListIterator <E>
hasNext():boolean;
next():E;
hasPrevious():boolean;
previous(): E;
nextIndex(): int;
previousIndex(): int;
remove():void;
set(E o): void;
add(E o): void;
- 26 -
Note!
Collection is an interface for an abstract data
type, Collections is a separate class for methods
operating on collections.
- 27 -
List: Example
TestArrayAndLinkedList.java
(course web page)
- 28 -
Map <K,V>
//BasicOperations
put(K,V):V;
get(K):V;
remove(K):V;
containsKey(K):boolean;
containsValue(V):boolean;
size():int;
isEmpty():boolean;
Entry <K,V>
getKey():K;
getValue():V;
setValue(V):V;
//BulkOperations
voidputAll(Mapt):void;
voidclear():void;
//CollectionViews
keySet():Set<K>;
values():Collection<V>;
entrySet():Set<Entry<K,V>>;
- 29 -
Map Examples
CountOccurranceOfWords.java
(course web page)
TestMap.java (from text)
- 30 -
Comparator Interface
(a generic class similar to Comparable)
(comparator slides adapted from Carl Reynolds)
- 31 -
Comparator<T> Interface
One method:
compare( T o1, T o2 )
Returns:
negative if o1 < o2
Zero
if o1 == o2
positive if o1 > o2
- 32 -
Example Comparator:
Compare 2 Strings regardless of case
import java.util.*;
public class CaseInsensitiveComparator implements Comparator<String> {
public int compare( String stringOne, String stringTwo ) {
// Shift both strings to lower case, and then use the
// usual String instance method compareTo()
return stringOne.toLowerCase().compareTo( stringTwo.toLowerCase() );
}
}
- 33 -
Using a Comparator...
Collections.sort( myList, myComparator );
Collections.max( myCollection, myComparator );
Set myTree = new TreeSet<String>( myComparator );
Map myMap = new TreeMap<String>( myComparator );
import java.util.*;
public class SortExample2B {
public static void main( String args[] ) {
List aList = new ArrayList<String>();
for ( int i = 0; i < args.length; i++ ) {
aList.add( args[ i ] );
}
Collections.sort( aList , new CaseInsensitiveComparator() );
System.out.println( aList );
}
}
- 34 -
...