You are on page 1of 38

Java Collections Framework

Authored by Alex Chaffee


Copyright © 1998 Purple Technology, Inc.
All rights reserved.
Licensed to Advanced Web Technologies

1.0t Vinay Nayudu 1


Java Collections Framework

Abstract Data Types


• Data Structures and Algorithms
• Standard
• Well-understood
• Efficient
• Examples
– Stack, queue, linked list

1.0t Vinay Nayudu 2


Java Collections Framework

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

1.0t Vinay Nayudu 3


Java Collections Framework

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

1.0t Vinay Nayudu 4


Java Collections Framework

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

1.0t Vinay Nayudu 5


Java Collections Framework

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

1.0t Vinay Nayudu 6


Java Collections Framework

Interface-Based Design
– interface List {…}
– class LinkedList implements List {…}
– …
– List l = new LinkedList();
– l.add( new Date() );
– Date d = (Date)l.get(0);

1.0t Vinay Nayudu 7


Java Collections Framework

Overview: Core Interfaces


• Collection
• Set
• List
• Map
• SortedSet
• SortedMap

1.0t Vinay Nayudu 8


Java Collections Framework

Overview: Utilities
• Utility Interfaces
– Comparator
– Iterator
• Utility Classes
– Collections
– Arrays

1.0t Vinay Nayudu 9


Java Collections Framework

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();

1.0t Vinay Nayudu 10


Java Collections Framework

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

1.0t Vinay Nayudu 11


Java Collections Framework

List
• interface List extends Collection
• An ordered collection of objects
• Duplicates allowed

1.0t Vinay Nayudu 12


Java Collections Framework

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

1.0t Vinay Nayudu 14


Java Collections Framework

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

Accessing all members of Map


• Methods
– Set keySet();
– Collection values();
– Set entrySet();
• Map.Entry
– Object that contains a key-value pair
• getKey(), getValue()
• Thread safety
– The collections returned are backed by the map
• When the map changes, the collection changes
– Behavior can easily become undefined
• Be very careful and read the docs closely
1.0t Vinay Nayudu 16
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

1.0t Vinay Nayudu 17


Java Collections Framework

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

1.0t Vinay Nayudu 18


Java Collections Framework

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)

1.0t Vinay Nayudu 19


Java Collections Framework

Set Implementations
• HashSet
– a Set backed by a hash table
• TreeSet
– A balanced binary tree implementation
– Imposes an ordering on its elements

1.0t Vinay Nayudu 20


Java Collections Framework

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

1.0t Vinay Nayudu 24


Java Collections Framework

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.

1.0t Vinay Nayudu 26


Java Collections Framework

Unsupported Operations
• An implementation class may elect not
to support a particular method of the
interface
• UnsupportedOperationException is a
runtime (unchecked) exception

1.0t Vinay Nayudu 27


Java Collections Framework

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

1.0t Vinay Nayudu 28


Java Collections Framework

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.

1.0t Vinay Nayudu 29


Java Collections Framework

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

1.0t Vinay Nayudu 31


Java Collections Framework
Thread safety

Synchronized Collections
• Wrapper implementations that
synchronize all relevant methods
• Factory methods inside the Collections
class
• Example:
– List list = Collections.synchronizedList(new
ArrayList(...));

1.0t Vinay Nayudu 32


Java Collections Framework
Thread safety

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(...));

1.0t Vinay Nayudu 33


Java Collections Framework
Thread safety

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

1.0t Vinay Nayudu 34


Java Collections Framework

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

1.0t Vinay Nayudu 35


Java Collections Framework

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

1.0t Vinay Nayudu 36


Java Collections Framework

Other cool stuff


• Singleton Set
• EMPTY_SET, EMPTY_LIST
• nCopies
• Arrays.asList

1.0t Vinay Nayudu 37


Java Collections Framework

Other Collections Frameworks


• Doug Lea
• JGL

1.0t Vinay Nayudu 38

You might also like