Collection Framework Module 02
Collection Framework Module 02
Framework
Santhosh SG
Module-2
Collections Overview, Recent Changes to Collections, The Collection Interfaces, The Collection
Classes, Accessing a collection Via an Iterator, Storing User Defined Classes in Collections, The
Random Access Interface, Working With Maps, Comparators, The Collection Algorithms, Why
Generic Collections?, The legacy Classes and Interfaces, Parting Thoughts on Collections.
Collections
• Collections framework was not a part of original Java release. Collections were
added to J2SE 1.2. Prior to Java 2.
• A collection in java is a framework that provides architecture to store and
manipulate the group of objects.
• All the operations that you perform on a data such as searching, sorting,
insertion, manipulation, deletion etc. can be performed by Java Collections.
• Java Collection simply means a single unit of objects.
• Java Collection framework provides many interfaces (Set, List, Queue, Deque
etc.) and classes (ArrayList, LinkedHashSet, TreeSet etc). Vector, LinkedList,
PriorityQueue, HashSet,
• Framework in java means hierarchy of classes and interfaces.
• Collections framework is contained in java.util package.
The Java Collections Framework
• A collection — sometimes called a container — is simply an object that groups
multiple elements into a single unit.
• Collections are used to store, retrieve, manipulate, and communicate aggregate
data.
• Typically, they represent data items that form a natural group, such as
• a poker hand (a collection of cards),
• a mail folder (a collection of letters), or
• a telephone directory (a mapping of names to phone numbers).
A collections framework is a unified architecture for representing and manipulating collections.
All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be
manipulated independently of the details of their representation. In object-oriented languages,
interfaces generally form a hierarchy.
Implementations: These are the concrete implementations of the collection interfaces. In essence,
they are reusable data structures.
Algorithms: These are the methods that perform useful computations, such as searching and sorting,
on objects that implement collection interfaces.
The algorithms are said to be polymorphic: that is, the same method can be used on many different
implementations of the appropriate collection interface. In essence, algorithms are reusable
functionality.
The Java Collections Framework
• An array is a very useful type in Java but it has its restrictions:
• once an array is created it must be sized, and this size is fixed;
• it contains no useful pre-defined methods.
• Java comes with a group of generic collection classes that grow as more elements
are added to them, and these classes provide lots of useful methods.
• This group of collection classes are referred to as the Java Collections Framework.
• The classes in the JCF are all found in the java.util package.
• Three important interfaces from this group are:
• List;
• Set;
• Map.
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all the classes and
interfaces for the Collection framework.
Types of Collection
• Java supplies several types of Collection:
• Set: cannot contain duplicate elements, order is not important
• SortedSet: like a Set, but order is important
• List: may contain duplicate elements, order is important
• While you can get all the details from the Java API, you are expected to
learn (i.e. memorize):
• The signatures of the “most important” methods in each interface
• The most important implementations of each interface
The Collections hierarchy
The Collection Interface
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and
access the elements from the list.
Give the syntax of collection interface. Explain the methods present in collection
interface.
interface Collection<E>
1. add
boolean add(E 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.
2. addAll
boolean addAll(Collection<? extends E> 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.
3. clear
void clear( )
Removes all elements from the invoking collection.
4. contains
boolean contains(Object obj )
Returns true if obj is an element of the invoking collection.
Otherwise, returns false.
5. containsAll
boolean containsAll(Collection<?> c )
Returns true if the invoking collection contains all elements of c.
Otherwise, returns false.
6. equals
boolean equals(Object obj )
Returns true if the invoking collection and obj are equal.
Otherwise, returns false.
7. hashCode
int hashCode( ) Returns the hash code for the invoking collection.
8. isEmpty
boolean isEmpty( )
Returns true if the invoking collection is empty.
Otherwise, returns false
9. iterator
Iterator<E> iterator( ) Returns an iterator for the invoking collection.
boolean remove(Object obj ) Removes one instance of obj from the invoking collection.
Returns true if the element was removed. Otherwise, returns false.
10. removeAll
boolean removeAll(Collection c ) Removes all elements of c from the invoking collection.
Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
11. retainAll
boolean retainAll(Collection c ) Removes all elements from the invoking collection except those
in c. Returns true if the collection changed (i.e., elements were removed). Otherwise, returns false.
12. size
int size( ) Returns the number of elements held in the invoking collection.
13. toArray
Object[ ] toArray( )
Returns an array that contains all the elements stored in the invoking collection.
The array elements are copies of the collection elements.
The array elements are copies of the collection elements.
If the size of array equals the number of elements, these are returned in array.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as
follows:
Recently, the Collections Framework underwent a fundamental change
Recent Changes to Collections
that significantly increased its power and streamlined its use.
The changes were caused by the
addition of generics,
autoboxing/unboxing, and
the for-each style for loop, by JDK5
peek() checks if the deque is not empty (returns the top element without removing it).
pop() removes and returns the top element.
This loop continues until the deque is empty.
Accessing a collection Via an Iterator:
Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to the start of the collection.
By using this iterator object, you can access each element in the collection. Element at a time. In
general, to use an iterator to cycle through the contents of a collection,
Note: Try yourself Write a java program to use Random Access Interface.
The Map Interfaces
The Map interface maps unique keys to values. A key is an object that you use to
retrieve a value at a later date. Given a key and a value, we can store the value in a
Map object. After the value is stored, you can retrieve it by using its key.
The map interfaces define the character and nature of maps.
Map is generic:
interface Map <K, V>
Here, K specifies the type of keys, and V specifies the type of values. The methods
declared by Map.
Working With Maps:
A map is an object that stores associations between keys and values, or
key/value pairs. Keys and values are objects. Keys must be unique, but the values
may be duplicated.
Some maps can accept a null key and null values, others cannot. There is one
key point about maps that is important to mention at the outset: they don’t
implement the Iterable interface. This means that you cannot cycle through a map
using a for-each style for loop. Furthermore, you can’t obtain an iterator to a map.
However, as you will soon see, you can obtain a collection-view of a map,
which does allow the use of either the for loop or an iterator.
A Map in Java is a collection that stores key-value pairs. Unlike List
and Set, a Map does not allow duplicate keys but can have duplicate
values.
Common implementations of Map in Java include(HLTH):
1. HashMap (unordered, fast)
2. LinkedHashMap (insertion order maintained)
3. TreeMap (sorted order)
4. Hashtable (synchronized, thread-safe)
HashMap:
The HashMap class extends AbstractMap and implements the Map interface. It uses a hash
table to store the map.
This allows the execution time of get( ) and put( ) to remain constant even for large sets.
HashMap is a generic class that has this declaration:
class HashMap<K, V>
Here, K specifies the type of keys, and V specifies the type of values.
The following constructors are defined:
1. HashMap( )
2. HashMap(Map<? extends K, ? extends V> m)
3. HashMap(int capacity)
4. HashMap(int capacity, float fillRatio)
HashMap implements Map and extends AbstractMap. It does not add any methods of its own.
// Iterating through the Map
1. Creating and Using a HashMap System.out.println("HashMap contents:");
for (Map.Entry<Integer, String> entry : map.entrySet()) {
Example: Basic Operations with HashMap System.out.println("Key: " + entry.getKey() + ", Value:
" + entry.getValue());
import java.util.*; }
}
class HashMapExample { }
public static void main(String[] args) {
// Creating a HashMap
HashMap<Integer, String> map = new HashMap<>();
TreeMap has no methods beyond those specified by the NavigableMap interface and the
AbstractMap class.
LinkedHashMap
LinkedHashMap extends HashMap.
It maintains a linked list of the entries in the map, in the 1order in which they were inserted. This
allows insertion-order iteration over the map. That is, when iterating through a collection-view of a
LinkedHashMap, the elements will be returned in the order in which they were inserted.
LinkedHashMap that returns its elements in the order in which they were last accessed.
LinkedHashMap is a generic class that has this declaration:
Here, obj is the object to be tested for equality. The method returns true if obj and
the invoking object are both Comparator objects and use the same ordering.
Otherwise, it returns false.
The Collection Algorithms:
Collections Framework defines several algorithms that can be applied to collections and
maps.
Algorithms are defined as static methods within the Collections class.
• static <T> Boolean addAll(Collection <? super T> c, T ... elements)
Inserts the elements specified by elements into the collection specified by c. Returns true if the
elements were added and false otherwise.
• static <T> Queue<T> asLifoQueue(Deque<T> c)
Returns a last-in, first-out view of c.
• static <T>int binarySearch(List<? extends T> list, T value, Comparator<? super T> c)
Searches for value in list ordered according to c. Returns the position of value in list, or a
negative value if value is not found.
• static <T> int binarySearch(List<? extends Comparable<? super T>> list,T value) Searches
for value in list. The list must be sorted. Returns the position of value in list, or a negative
value if value is not found.
• static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> t)
Returns a run-time type-safe view of a collection. An attempt to insert an incompatible element
will cause a ClassCastException.
• static <K, V> Map<K, V> checkedMap(Map<K, V> c, Class<K> keyT, Class<V> valueT)
Returns a run-time type-safe view of a Map. An attempt to insert an incompatible element will
cause a ClassCastException.
• static int frequency(Collection c, Object obj) Counts the number of occurrences of obj in c
and returns the result.
• static int indexOfSubList(List<?> list, List<?> subList)
Searches list for the first occurrence of subList. Returns the index of the first match, or –1 if no
match is found.
The reason for this is that generics add type safety to the Collections
Framework. Before moving on, it is worth taking some time to examine in detail
the significance of this improvement.
The Legacy Classes and Interfaces
Early version of java did not include the Collections framework. It only defined several
classes and interfaces that provide methods for storing objects. When Collections framework
were added in J2SE 1.2, the original classes were reengineered to support the collection interface.
These classes are also known as Legacy classes.
All legacy classes and interface were redesign by JDK 5 to support Generics. In general, the
legacy classes are supported because there is still some code that uses them.
The following are the legacy classes defined by java.util package
1. Dictionary
2. HashTable
3. Properties
4. Stack
5. Vector
There is only one legacy interface called Enumeration
NOTE: All the legacy classes are synchronized
Enumeration interface
1. Enumeration interface defines method to enumerate(obtain one at a time)
through collection of objects.
2. This interface is superseded(replaced) by Iterator interface.
3. However, some legacy classes such as Vector and Properties defines several
method in which Enumeration interface is used.
4. It specifies the following two methods.
1. boolean hasMoreElements()
//It returns true while there are still more elements to extract, and returns false when all the
elements have been enumerated.
2. Object nextElement()
//It returns the next object in the enumeration i.e. each call to nextElement() method obtains the
next object in the enumeration. It throws NoSuchElementException when the enumeration is
complete.
Vector class
1. Vector is similar to ArrayList which represents a dynamic array.
2. There are two differences between Vector and ArrayList. First, Vector is synchronized
while ArrayList is not, and Second, it contains many legacy methods that are not part of the
Collections Framework.
3. With the release of JDK 5, Vector also implements Iterable. This means that Vector is fully
compatible with collections, and a Vector can have its contents iterated by the for-each loop.
4. Vector class has following four constructor
• Vector() //This creates a default vector, which has an initial size of 10.
• Vector( int size ) //This creates a vector whose initial capacity is specified by size.
• Vector(int size, int incr) //This creates a vector whose initial capacity is specified by size
and whose increment is specified by incr. The increment specifies the number of elements
to allocate each time when a vector is resized for addition of objects.
Here, E specifies the type of element stored in the stack. Stack includes all the
methods defined by Vector.
Dictionary
Dictionary is an abstract class that represents a key/value storage repository and
operates much like Map.
Given a key and value, we can store the value in a Dictionary object. Once the
value is stored, we can retrieve it by using its key. Thus, like a map, a dictionary
can be thought of as a list of key/value pairs.
Although not currently deprecated, Dictionary is classified as obsolete, because it is
fully superseded by Map. However, Dictionary is still in use and thus, is fully
discussed here.
Here, K specifies the type of keys, and V specifies the type of values.
Parting Thoughts on Collections
The Collections Framework gives you, the programmer, a powerful set of well-engineered
solutions to some of programming’s most common tasks. Consider using a collection the next
time that you need to store and retrieve information. Remember, collections need not be reserved
for only the “large jobs,” such as corporate databases, mailing lists, or inventory systems. They
are also effective when applied to smaller jobs.
For example, a TreeMap might make an excellent collection to hold the directory
structure of a set of files. A TreeSet could be quite useful for storing project-management
information.
The Java Collection Framework is a powerful tool that simplifies data manipulation, but
choosing the right collection and applying best practices can significantly impact application
performance. Understanding when and how to use each collection ensures efficient memory
usage, scalability, and maintainability of Java applications.
The End
Summary :
The Java Collection Framework (JCF)
provides a unified architecture for storing,
manipulating, and processing data efficiently. It
includes interfaces (List, Set, Queue, Map),
implementations (ArrayList, HashSet,
TreeMap), and algorithms (sorting, searching).
JCF improves performance, scalability, and
flexibility in Java applications by offering dynamic
and optimized data structures.