Professional Documents
Culture Documents
Interface-based design
• Separate interface from implementation
• Built in to Java language
• Polymorphism
– List l = new LinkedList();
– Calling l.add() invokes method of class
LinkedList
Collections Framework
• Interoperability between unrelated APIs
• Reduces the effort required to learn
APIs
• Reduces the effort required to design
and implement APIs
• Fosters software reuse
Project Goals
• Small API
– Number of interfaces
– Number of methods per interface
– Low "conceptual weight"
• Builds on existing Java collections
(Vector, Hashtable)
• Interconvertible with Java arrays
Collections Availability
• Ships with JDK 1.2
– Due to ship (FCS) by the end of 1998
• An early-release JDK 1.1 compatible
version is available
– Was needed for the InfoBus 1.1 specification
– Get it at
http://www.javasoft.com/beans/infobus/index.html
– See http://www.javasoft.com/beans/infobus/
collectionsreadme.html for more information
Interface-Based Design
– interface List {…}
– class LinkedList implements List {…}
– …
– List l = new LinkedList();
– l.add( new Date() );
– Date d = (Date)l.get(0);
Overview: Utilities
• Utility Interfaces
– Comparator
– Iterator
• Utility Classes
– Collections
– Arrays
Collection
• A group of objects
• Major methods:
– int size();
– boolean isEmpty();
– boolean contains(Object);
– Iterator iterator();
– Object[] toArray();
– boolean add(Object);
– boolean remove(Object);
– void clear();
Set
• interface Set extends Collection
• An unordered collection of objects
• No duplicate elements
• Same methods as Collection
– Semantics are different, so different interface
needed for design
• Implemented by:
– HashSet, TreeSet
List
• interface List extends Collection
• An ordered collection of objects
• Duplicates allowed
List Details
• Major additional methods:
– Object get(int);
– Object set(int, Object);
– int indexOf(Object);
– int lastIndexOf(Object);
– void add(int, Object);
– Object remove(int);
– List subList(int, int);
• add() inserts
• remove() deletes
• Implemented by:
– ArrayList, LinkedList, Vector
1.0t Vinay Nayudu 13
Java Collections Framework
Map
• interface Map (does not extend
Collection)
• An object that maps keys to values
• Each key can have at most one value
• Replaces java.util.Dictionary interface
• Ordering may be provided by
implementation class, but not
guaranteed
Map Details
• Major methods:
– int size();
– boolean isEmpty();
– boolean containsKey(Object);
– boolean containsValue(Object);
– Object get(Object);
– Object put(Object, Object);
– Object remove(Object);
– void putAll(Map);
– void clear();
• Implemented by:
– HashMap, Hashtable, WeakHashMap,
Attributes
1.0t Vinay Nayudu 15
Java Collections Framework
Iterator
• Represents a loop
• Created by Collection.iterator()
• Similar to Enumeration
– Improved method names
– Allows a remove() operation on the current item
Iterator Methods
• boolean hasNext()
– Returns true if the iteration has more elements
• Object next()
– Returns next element in the iteration
• void remove()
– Removes the current element from the
underlying Collection
ListIterator
• interface ListIterator extends Iterator
• Created by List.listIterator()
• Adds methods to
– traverse the List in either direction
– modify the List during iteration
• Methods added:
– hasPrevious(), previous()
– nextIndex(), previousIndex()
– set(Object), add(Object)
Set Implementations
• HashSet
– a Set backed by a hash table
• TreeSet
– A balanced binary tree implementation
– Imposes an ordering on its elements
List Implementations
• ArrayList
– a resizable-array implementation like Vector
• unsynchronized, and without legacy methods
• LinkedList
– a doubly-linked list implementation
– May provide better performance than ArrayList
• if elements frequently inserted/deleted within the List
– For queues and double-ended queues (deques)
• Vector
– a synchronized resizable-array implementation
of a List with additional "legacy" methods.
1.0t Vinay Nayudu 21
Java Collections Framework
Map Implementations
• HashMap
– A hash table implementation of Map
– Like Hashtable, but supports null keys & values
• TreeMap
– A balanced binary tree implementation
– Imposes an ordering on its elements
• Hashtable
– Synchronized hash table implementation of Map
interface, with additional "legacy" methods.
1.0t Vinay Nayudu 22
Java Collections Framework
WeakHashMap
• WeakHashMap
– Special-purpose implementation of Map
interface storing only weak references to its
keys
– Allows key-value pairs to be garbage-collected
when the key is no longer referenced outside of
the WeakHashMap
– Useful for implementing "registry-like" data
structures, where the utility of an entry vanishes
when its key is no longer reachable by any
1.0t thread. Vinay Nayudu 23
Java Collections Framework
Sorting
• Collections.sort() static method
• SortedSet, SortedMap interfaces
– Collections that keep their elements sorted
– Iterators are guaranteed to traverse in sorted
order
• Ordered Collection Implementations
– TreeSet, TreeMap
Sorting (cont.)
• Comparable interface
– Must be implemented by all elements in SortedSet
– Must be implemented by all keys in SortedMap
– Method: int compareTo(Object o)
– Defines "natural order" for that object class
• Comparator interface
– Defines a function that compares two objects
– Can design custom ordering scheme
– Method: int compare(Object o1, Object o2)
1.0t Vinay Nayudu 25
Java Collections Framework
Sorting (cont.)
• Total vs. Partial Ordering
– Technical, changes behavior per object class
• Sorting Arrays
– Use Arrays.sort(Object[])
– Equivalent methods for all primitive types
• Arrays.sort(int[]), etc.
Unsupported Operations
• An implementation class may elect not
to support a particular method of the
interface
• UnsupportedOperationException is a
runtime (unchecked) exception
Ch-ch-ch-ch-changes
• Modifiable/Unmodifiable
– Modifiable: Collections that support modification
operations, e.g., add(), remove(), clear()
– Unmodifiable: Collections that do not support any
modification operations
• Mutable/Immutable
– Immutable: Collections that guarantee that no change in
the Collection will ever be observable via "query"
operations, e.g., such as iterator(), size(), contains()
– Mutable: Collections that are not immutable
More Changes
• Fixed-size/Variable-size
– Lists that guarantee that their size will remain
constant even though the elements may change
are referred to as fixed-size.
– Lists that are not fixed-size are referred to as
variable-size.
Thread safety
• Collections, by default, are NOT thread-
safe
• Design decision for performance and
"conceptual weight"
• Solutions:
– Encapsulated Collections
– Synchronized Collections
– Unmodifiable Collections
– Fail-fast iterators
1.0t Vinay Nayudu 30
Java Collections Framework
Thread safety
Encapsulated Collections
• In general, if the only access to a
collection is through a thread-safe
object, then that collection is safe
Synchronized Collections
• Wrapper implementations that
synchronize all relevant methods
• Factory methods inside the Collections
class
• Example:
– List list = Collections.synchronizedList(new
ArrayList(...));
Unmodifiable Collections
• If an object can't be modified, it is
thread-safe by definition
• Factory methods inside the Collections
class
• Example:
– List list = Collections.unmodifiableList(new ArrayList(...));
Fail-fast Iterators
• If collection is modified during the life of
an iterator, then that iterator fails
immediately
• Rather than risking arbitrary, non-
deterministic behavior at an
undetermined time in the future
• Exception: the iterator's own add() and
remove() methods work fine
Utility Classes
• Collections class
• Static methods:
– sort(List)
– binarySearch(List, Object)
– reverse(List)
– shuffle(List)
– fill(List, Object)
– copy(List dest, List src)
– min(Collection)
– max(Collection)
– synchronizedX, unmodifiableX factory methods
Utility Classes
• Arrays class
• Static methods that act on Java arrays:
– sort
– binarySearch
– equals
– fill
– asList - returns an ArrayList composed of this
array's contents