Unit I - Collection
Unit I - Collection
Unit I - Collection
Collections
Collections Overview
• The Java Collections Framework standardizes the way in which groups
of objects are handled by your programs.
• added by J2SE 1.2
• Prior it was Dictionary, Vector, Stack, and Properties classes.
• These classes unifying theme lacked a central, e.g. the way that you
used Vector was different from the way that you used Properties.
• Java.util package contains al the classes and interfaces of collection
framework.
Goals of Collection Framework
• The framework had to be high-performance.
• The implementations for the fundamental collections (dynamic arrays,
linked lists, trees, and hash tables) are highly efficient. You seldom, if
ever, need to code one of these “data engines” manually.
• The framework had to allow different types of collections to work in a
similar manner and with a high degree of interoperability.
• Extending and/or adapting a collection is easy.
The Collection Interfaces
• The entire Collections Framework is built upon a set of standard
interfaces such as LinkedList, HashSet, and TreeSet etc.
• In addition to the collection interfaces, collections also use the
Comparator, RandomAccess, Iterator, and ListIterator interfaces.
• The collection interfaces allow some optional methods that enable
you to modify the contents of a collection. These methods are called
modifiable.
• Collections that do not allow their contents to be changed are called
unmodifiable.
• If an attempt is made to use one of these methods on an unmodifiable
collection, an UnsupportedOperationException is thrown.
The Collection Interface
• The Collection interface must be implemented by any class that
defines a collection.
• Collection extends the Iterable interface. This means that all
collections can be cycled through.
Method Description
boolean add(Object obj) Adds obj to the invoking collection. Returns true if obj was added to
the collection. Returns false if obj is already a member of the
collection and the collection does not allow duplicates.
boolean addAll(Collection c) Adds all the elements of c to the invoking collection. Returns true if
the operation succeeded (i.e., the elements were added).
Otherwise, returns false.
boolean equals(Object obj) Returns true if the invoking collection and obj are equal. Otherwise,
returns false.
int hashCode( ) Returns the hash code for the invoking collection.
boolean isEmpty( ) Returns true if the invoking collection is empty. Otherwise, returns
false.
Method Description
boolean remove(Object Removes one instance of obj from the invoking collection.
obj) Returns true if the element was removed. Otherwise,
returns false.
boolean Removes all elements of c from the invoking collection.
removeAll(Collection c) Returns true if the collection changed (i.e., elements were
removed). Otherwise, returns false.
void add(int index, E obj) Inserts obj into the invoking list at the index passed in
index. Any preexisting elements at or beyond the point
of insertion are shifted up. Thus, no elements are
overwritten.
boolean addAll(int index, Inserts all elements of c into the invoking list at the
Collection<? extends E> index passed in index. Any preexisting elements at or
c) beyond the point of insertion are shifted up. Thus, no
elements are overwritten. Returns true if the invoking
list changes and returns false otherwise.
E get(int index) Returns the object stored at the specified index within
the invoking collection.
int indexOf(Object obj) Returns the index of the first instance of obj in the
invoking list. If obj is not an element of the list, –1 is
returned.
Method Description
int lastIndexOf(Object Returns the index of the last instance of obj in the
obj) invoking list. If obj is not an element of the list, –1 is
returned.
Comparator<? super E> Returns the invoking sorted set’s comparator. If the
comparator( ) natural ordering is used for this set, null is returned.
boolean offer(E obj) Attempts to add obj to the queue. Returns true if obj was
added and false otherwise.
void clear( ) Removes all key/value pairs from the invoking map.
boolean equals(Object Returns true if obj is a Map and contains the same
obj) entries. Otherwise, returns false.
Method Description
V get(Object k) Returns the value associated with the key k. Returns null if
the key is not found.
int hashCode( ) Returns the hash code for the invoking map.
Collection<V> values( ) Returns a collection containing the values in the map. This
method provides a collection-view of the values in the
map.
The Collection Classes
Class Description
ArrayList( )
ArrayList(Collection<? extends E> c)
ArrayList(int capacity)
The LinkedList Class
• The LinkedList class extends AbstractSequentialList class.
• It implements the List, Deque, and Queue interfaces.
• It provides a linked-list data structure.
• Constructors:
LinkedList( )
LinkedList(Collection<? extends E> c)
The HashSet Class
• HashSet extends AbstractSet class.
• It implements the Set interface.
• It creates a collection that uses a hash table for storage.
• Constructors:
HashSet( )
HashSet(Collection<? extends E> c)
HashSet(int capacity)
• In hashing, the informational content of a key is used to
determine a unique value, called its hash code.
• The hash code is then used as the inde0x at which the data
associated with the key is stored.
• The transformation of the key into its hash code is performed
automatically— you never see the hash code itself.
• Also, your code can’t directly index the hash table.
• The advantage of hashing is that it allows the execution time
of add( ), contains( ), remove( ), and size( ) to remain constant
even for large sets.
The LinkedHashSet Class
• The LinkedHashSet class extends HashSet and adds no members of its
own.
• LinkedHashSet maintains a linked list of the entries in the set, in the
order in which they were inserted.
• That is, when cycling through a LinkedHashSet using an iterator, the
elements will be returned in the order in which they were inserted.
The TreeSet Class
• TreeSet extends AbstractSet and implements the NavigableSet interface.
• It creates a collection that uses a tree for storage.
• Objects are stored in sorted, ascending order.
• Access and retrieval times are quite fast, which makes TreeSet an
excellent choice when storing large amounts of sorted information that
must be found quickly.
• Constructors:
TreeSet( )
TreeSet(Collection<? extends E> c)
TreeSet(Comparator<? super E> comp)
TreeSet(SortedSet<E> ss)
The Map Classes
• Map classes provide implementations of the Map interfaces.
Class Description
HashMap( )
HashMap(Map<? extends K, ? extends V> m)
HashMap(int capacity)
The TreeMap Class
• The TreeMap class extends AbstractMap and implements the
NavigableMap interface.
• It creates maps stored in a tree structure.
• A TreeMap provides an efficient means of storing key/value pairs in
sorted order and allows rapid retrieval.
• Unlike a hash map, a tree map guarantees that its elements will be
sorted in ascending key order.
TreeMap( )
void add(E obj) Inserts obj into the list in front of the element that will be
returned by the next call to next( ).
boolean hasNext( ) Returns true if there is a next element. Otherwise, returns false.
void addElement(E element) The object specified by element is added to the vector.
boolean contains(Object element) Returns true if element is contained by the vector, and returns
false if it is not.
void copyInto(Object array[ ]) The elements contained in the invoking vector are copied into the
array specified by array.
int indexOf(Object element) Returns the index of the first occurrence of element. If the object
is not in the vector, –1 is returned.
int indexOf(Object element, int Returns the index of the first occurrence of element at or after
start. If the object is not in that portion of the vector, –1 is
start) returned.
boolean isEmpty( ) Returns true if the vector is empty, and returns false if it contains
one or more elements.
E lastElement( ) Returns the last element in the vector.
int lastIndexOf(Object element) Returns the index of the last occurrence of element. If the object
is not in the vector, –1 is returned.
int lastIndexOf(Object element, Returns the index of the last occurrence of element before start.
int start) If the object is not in that portion of the vector, –1 is returned.
void removeAllElements( ) Empties the vector. After this method executes, the size of the
vector is zero.
void removeElementAt(int index) Removes the element at the location specified by index.
void setElementAt(E element,
The location specified by index is assigned element.
int index)
void trimToSize( ) Sets the vector’s capacity equal to the number of elements that
it currently holds.
Hashtable
• Hashtable was part of the original java.util and is a concrete
implementation of a Dictionary.
• With the advent of collections, Hashtable was reengineered to also
implement the Map interface.
• Thus, Hashtable is now integrated into the Collections Framework.
• It is similar to HashMap, but is synchronized.
• Like HashMap, Hashtable stores key/value pairs in a hash table.
• However, neither keys nor values can be null.
• When using a Hashtable, you specify an object that is used as a key,
and the value that you want linked to that key.
• The key is then hashed, and the resulting hash code is used as the
index at which the value is stored within the table.
• Constructors:
Hashtable( )
• default constructor, creates a hash table.
Hashtable(int size)
• creates a hash table that has an initial size specified by size.
• The default size is 11.
Hashtable(int size, float fillRatio)
• creates a hash table that has an initial size specified by size and a
fill ratio specified by fillRatio.
• This ratio must be between 0.0 and 1.0
• It determines how full the hash table can be before it is resized
upward.
• When the number of elements is greater than the capacity of the
hash table multiplied by its fill ratio, the hash table is expanded.
• If you do not specify a fill ratio, then 0.75 is used
boolean contains(Object Returns true if some value equal to value exists within the hash
value) table. Returns false if the value isn’t found.
boolean containsKey(Object Returns true if some key equal to key exists within the hash table.
key) Returns false if the key isn’t found.
boolean containsValue(Object Returns true if some value equal to value exists within the hash
value) table. Returns false if the value isn’t found.
Enumeration<V> elements( ) Returns an enumeration of the values contained in the hash table.
Returns the object that contains the value associated with key.
V get(Object key)
If key is not in the hash table, a null object is returned.
boolean isEmpty( ) Returns true if the hash table is empty; returns false if it contains at
least one key.
Enumeration<K> keys( ) Returns an enumeration of the keys contained in the hash table.
Inserts a key and a value into the hash table. Returns null if key isn’t
V put(K key, V value) already in the hash table; returns the previous value associated with
key if key is already in the hash table.
void rehash( ) Increases the size of the hash table and rehashes all of its keys.
V remove(Object key) Removes key and its value. Returns the value associated with key. If key is
not in the hash table, a null object is returned.