0% found this document useful (0 votes)
5 views

MCA Java Programming 12(2)

This document provides an overview of the Java Collections Framework, detailing its interfaces, classes, and methods for organizing and manipulating groups of objects. It covers learning objectives and outcomes related to collections, including the use of iterators, maps, and generic classes. Additionally, it discusses the evolution of the framework, highlighting the introduction of generics and the importance of type safety in collections.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

MCA Java Programming 12(2)

This document provides an overview of the Java Collections Framework, detailing its interfaces, classes, and methods for organizing and manipulating groups of objects. It covers learning objectives and outcomes related to collections, including the use of iterators, maps, and generic classes. Additionally, it discusses the evolution of the framework, highlighting the introduction of generics and the importance of type safety in collections.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 42

UNIT

12 The Collections Framework

Names of Sub-Units

Collections Overview, 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

Overview
In this unit, we will take a look at the collections framework in Java, which are supported by java.
util package. As you can infer from the name, collection lets you group elements in various ways.
The collections framework provides various interfaces, classes and methods that make easier way of
working with items. These interfaces and classes are important, not just for their utility, but because
many other Java methods, use or return objects of these classes, such as the ArrayList and HashMap
classes.

Learning Objectives

In this unit, you will learn to:


 Define collections
 Use different Collection interfaces and classes
 Use of iterator in collection
 Explore the use of Maps
 Analyse the use of generic classes
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Learning Outcomes

At the end of this unit, you would:


 Create programs using different Collection interfaces and classes
 Work with Maps
 Create programs using Generic classes
 Explain different Collection algorithms
 Create programs using the legacy classes and interfaces

Pre-Unit Preparatory Material

 http://pages.di.unipi.it/corradini/Didattica/PR2-B-14/Java%20Collections%20Framework.pdf

12.1 INTRODUCTION
A collection is an object that organises multiple data items into a single group. In real-life scenarios, a
record of phone numbers that is required by you are kept in the mobile phonebook. You can also add
or remove a contact, or locate a contact, as per your requirement. Similarly, in Java while writing an
application, you may require to handle multiple interrelated data items. Therefore, the Java collections
framework is a standardised way wherein a group of objects is handled by programs.
Collections in Java are not type-safe in nature and thereby the concept of generics was introduced to
the evolution of Java 5. This unit discusses about collections, the creation of your own generic class and
methods, with the implementation of wildcards.

12.2 COLLECTIONS FRAMEWORK


In Java, a group of objects is represented as a collection. The collection framework provides a standardised
way to handle a group of objects. Collections store, retrieve and manipulate the collection of data items.
Here, a collection of data implies the formation of a natural group of data items, such as collection of
cards, collection of letters, collection of books and collections of contacts, in your mobile phone.
The collections framework provides lists, sets, maps and queues to perform multiple tasks related to the
group of objects. In Java, collections help in:
 Adding objects to a collection
 Removing objects from a collection
 Locating an object in a collection
 Retrieving an object from a collection
 Looking at each element of collection by iterating through the collection

The collections framework defines several interfaces and classes provided under the java.util package.
The Collections API comprises numerous interfaces and concrete classes. The Collection interface (java.
util.Collection) and Map interface (java.util.Map) are the two main “root” interfaces of Java collection
classes.

2
UNIT 12: The Collections Framework JGI JAIN DEEMED-TO-BE UNIVERSIT Y

Figure 1 shows the hierarchy structure for collections:

Iterable

Collection
e
Map extends
<Interface> I
List Queue Set Implement

ArrayList PriorityQueue HashSet HashTable I e SorteMap


<Class> <Interface>
LinkedList Deque LinkedHashSet

Vector ArrayDeque SortedSet


HashMap I TreeMap
Stack TreeSet <Class> <Class>

Figure 1: Hierarchy Structure of Collection Classes and Interfaces


Here are collection interfaces (Figure 1):
 Collection: It is the top of the collection hierarchy. It supports basic grouping of elements.
 List: It extends Collection to implement lists of objects.
 Set: It extends Collection to implement sets, in which all elements must be unique.
 Queue: It extends Collection to handle special type of lists.
 Deque: It extends Queue to handle a double-ended queue. (Added in Java SE 6).
 SortedSet: It extends Set to implement a sorted set.
 Map: It does not have duplicate keys and each key should map to at least one value. This interface
generally maps values with keys.
 SortedMap: It extends Map to implement a sorted map.

12.3 CHANGES TO COLLECTIONS


Prior to Java 2, ad hoc classes, such as Dictionary, Vector Stack and Properties, were used to store and
manipulate groups of objects. Although these classes were useful, but due to the lack of a central and
unifying approach in using these classes, there arose the need for a framework to handle groups of
objects. A framework is a set of classes and interfaces which provide a ready-made architecture. As a
result, the collections framework was introduced in Java, with the release of JDK 1.2 and then expanded
in the advanced versions of Java.
The Collections Framework has gone a fundamental modification that increased its power and
streamlined its use significantly. The changes were caused by the addition of generics, autoboxing/
unboxing and the for-each style for loop, by JDK 5.
The addition of generics has caused substantial modifications to the Collections Framework because
the whole Collections Framework has been changed for it. All collections are now generic, and many of
the methods that operate on collections take generic type parameters. Generics include the one feature
that had been missed by the collections that is type safety. Before generics, all collections stored Object
references, which meant that any collection could store any type of object. Therefore, it was possible to

3
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

store incompatible types in a collection accidentally due to which run-time type mismatch errors might
occur.
As generics allow you to explicitly state the type of data being stored, and therefore, run-time type
mismatch errors can be avoided. Although inclusion of generics has changed the declarations of most
of its classes and interfaces, and some of their methods, but, the Collections Framework still functions
the same as it did earlier to generics.

12.4 THE COLLECTION INTERFACES


The Collection interface revolves around the objects to provide maximum generality. For example, all
general-purpose collection executions have a constructor that takes the Collection parameter. This
constructor, known as a conversion constructor, initialises the new collection to hold all of the elements
in the intended location, whatever be the collection’s subinterface or implementation type. You can say
that it permits you to convert the collection’s type.
The foundation of the collection framework is the Collection interface, and because the collection classes
implement this interface, we will take a look at its methods here for reference.
You will find the methods for the Collection interface in Table 1:

Table 1: Methods of the Collection interface

Method Does this


boolean add(E e) It adds the given element.
boolean addAll It adds all the elements in the given collection.
(Collection c)
void clear() It removes all the elements from this collection.
boolean contains(E e) It returns True if this collection contains the given element.
boolean containsAll(Collection c) It returns True if this collection contains all the elements in the
given collection.
boolean equals(E e) It compares the given object with this collection for equality.
int hashCode() It gets the hashcode value for this collection.
boolean isEmpty() It returns True if this collection has no elements.
Iterator iterator() It gets an iterator over the elements in this collection.
boolean remove(E e) It removes a single instance of the given element.
boolean removeAll(Collection c) It removes all of this collection’s elements that are also contained
in the given collection (Optional Operation).
default boolean removeIf(Predicate<? It removes all the elements of this collection, which satisfy the
super E> filter) given predicate.
boolean retainAll(Collection c) It keeps only the elements in this collection, which are contained in
the given collection (Optional Operation).
int size() It gets the number of elements in this collection.
default Spliterator<E> HYPERLINK “http:// It creates a Spliterator over the elements in this collection.
docs.oracle.com/javase/8/docs/api/java/
util/Collection.html” \l “spliterator--”
spliterator()

4
UNIT 12: The Collections Framework JGI JAINDEEMED-TO-BE UNIVERSIT Y

Method Does this


default Stream<E> stream() It returns a sequential Stream with this collection as its source.
Object[] toArray() It gets an array containing all the elements in this collection.
<T> T[] toArray(T[ ] a) It gets an array containing all the elements in this collection whose
type is that of the given array.

12.4.1 The List Interface


The List interface is the foundation of classes, such as LinkedList and ArrayList. It is basically an
extension of the Collection interface that stores the behaviour of a collection. So, we will take a look at
the methods of this interface for reference. The methods of the List interface are provided in Table 2:

Table 2: Methods of the List interface

Method Does this


void add It inserts the given element at the given position in this list.
(int index, E element)
boolean add(E e) It adds the given element to the end of this list.
boolean addAll(Collection<? extends E> c) It adds all the elements in the given collection to the end of this list.
boolean addAll(int index, Collection<? It inserts all the elements in the given collection into this list.
extends E> c)
void clear() It removes all the elements from this list.
boolean contains(Object o) It returns True if this list contains the given element.
boolean containsAll It returns True if this list contains all the elements of the given
(Collection<?> c) collection.

boolean equals(Object o) It compares the given object with this list for equality.
Object get(int index) It gets the element at the given position in this list.
int hashCode() It gets the hashcode value for this list.
int indexOf(Object o) It gets the index of the first occurrence of the given element in this
list or -1 if this list does not contain the element.
boolean isEmpty() It returns True if this list contains no elements.
Iterator iterator() It gets an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o) It gets the index of the last occurrence of the given element in this
list or -1 if this list does not contain the element.
ListIterator listIterator() It gets a list iterator over the elements in this list (in proper
sequence).
ListIterator listIterator It gets a list iterator of the elements in this list, starting at the given
(int index) position in this list.

Object remove(int index) It removes the element at the given position in this list.
boolean remove(Object o) It removes the first occurrence in this list of the given element.
boolean removeAll It removes from this list all of its elements that are contained in the
(Collection<?> c) given collection (optional operation).

5
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


default replaceAll(UnaryOperator<E> It replaces each element of this list with the result of applying the
operator) operator to that element.
boolean retainAll It keeps only the elements in this list that are contained in the given
(Collection<?> c) collection.

E set(int index, E element) It replaces the element at the given position in the list with the new
element.
int size() It gets the number of elements in this list.
default void sort(Comparator<? super E> It sorts this list according to the order induced by the specified
c) Comparator.
default Spliterator<E> spliterator() It creates a Spliterator over the elements in this list.
List<E> subList(int fromIndex, int toIndex) It returns a view of the portion of this list between the specified
fromIndex, inclusive and toIndex, exclusive.
List subList(int fromIndex, int toIndex) It gets a view of the section between the given fromIndex (inclusive)
and toIndex.
Object[] toArray() It gets an array containing all the elements in this list in proper
sequence (from first to last element).
<T> T[] toArray It gets an array containing all the elements in this list in proper
(T[ ] a) sequence (from first to last element); the runtime type of the
returned array is that of the specified array.

12.4.2 The Set Interface


The Set interface is the foundation of classes, such as HashSet and TreeSet, and it is used by the collection
framework to implement sets. Therefore, we will take a look at this interface for reference. The methods
of the Set interface are provided in Table 3:

Table 3: Methods of the Set Interface

Method Does this


boolean add(E e) It adds the given element to this set.
boolean addAll (Collection<? extends E> It adds all the elements in the given collection.
c)
void clear() It removes all the elements from this set.
boolean contains(Object o) It returns True if this set contains the given element.
boolean containsAll It returns True if this set contains all the elements of the given
(Collection<?> c) collection.

boolean equals(Object o) It compares the given object with this set for equality.
int hashCode() It gets the hashcode value for this set.
boolean isEmpty() It returns True if this set contains no elements.
Iterator iterator() It gets an iterator over the elements in this set.
boolean remove(Object o) It removes the given element from this set if it is present.

6
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


boolean removeAll It removes all elements contained in the given collection.
(Collection<?> c)
boolean retainAll It keeps only the elements in this set that are contained in the given
(Collection<?> c) collection.

int size() It gets the number of elements in this set (its cardinality).
Object[] toArray() It gets an array containing all the elements in this set.
<T> T[] toArray It gets an array containing all the elements in this set whose runtime
(T[ ] a) type is that of the given array.

12.4.3 The SortedSet Interface


The SortedSet interface maintains a sorted set, and you will find the methods of this interface in Table 4:

Table 4: Methods of the SortedSet Interface

Method Does this


Comparator<? Super E> comparator() It returns the comparator used to order the elements in this set or
null if this set uses the natural ordering.
E first() It gets the first (lowest) element currently in this set.
SortedSet headSet It gets a view of the section of this set whose elements are strictly less
(Object toElement) than toElement.

E last() It gets the last (highest) element currently in this set.


default Spliterator<E> spliterator() It creates a Spliterator over the elements in this sorted set.
SortedSet<E> subSet It gets a view of the portion of this set whose elements range from
(E fromElement, E toElement) fromElement to toElemen.

SortedSet<E> tailSet It gets a view of the portion of this set whose elements are greater
(E fromElement) than or equal to fromElement.

12.4.4 The Queue Interface


A Queue is a collection of elements to hold them before processing starts. Besides basic Collection
operations, queues provide additional insertion, deletion and inspection operations. The Queue interface
follows:
public interface Queue<E> extends Collection<E>
{
E element();
boolean offer(E e);
E peek();
E poll();
E remove();
}

7
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Each Queue method exists in the following two forms:


1. It throws an exception if the operation fails.
2. It returns a special value if the operation fails (either null or false, depending on the operation).

The methods of the Queue interface are listed in Table 5:

Table 5: Methods of the Queue interface

Method Does this


boolean add(E e) It inserts specified elements into this queue and returns true. If no
available space, then it throws an IllegalStateExcetion.
E element() It retrieves and returns the element at the head of this queue.
boolean offer(E e) Ii inserts element and returns true if the element is inserted into the
queue.
E peek () It returns the item at the head of this queue without removing it from
the queue. It throws an exception if the queue is empty and returns null.
E pool() It retrieves and removes the head of this queue. If the queue is empty,
then it returns null.
E remove() It retrieves and removes the head of this queue.

12.4.5 The Deque Interface


This interface is similar to as a Queue interface with the difference is that it allows insertion, extraction
and inspection at both ends. Deques can be used both as FIFO (first-in, first-out) and LIFO (last-in, first-
out). Some noteworthy methods of the Deques interface are listed in Table 6:

Table 6: Methods of the deque interface

Method Does this


addFirst() It adds the specified element at the beginning of the deque and throws an exception in
case the deque is full.
addLast() It adds the specified element at the end of the deque and throws an exception in case
the deque is full.
offerFirst() It adds the specified element at the beginning of the deque and returns false in case the
deque is full.
offerLast() It adds the specified element at the end of the deque and returns false in case the deque
is full.
getFirst() It returns the first element of the deque, but throws an exception in case the deque is
empty.
getLast() It returns the last element of the deque, but throws an exception in case the deque is
empty.
peekFirst() It returns the first element of the deque and return null in case the deque is empty.
peekLast() It returns the last element of the deque and returns null in case the deque is empty.
removeFirst() It returns and removes the first element of the deque, but throws an exception if the
deque is empty.

8
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


removeLast() It returns and removes the last element of the deque, but throws an exception if the
deque is empty.
pollFirst() It returns and removes the first element of the deque and returns null in case the deque
is empty.
pollLast() It returns and removes the last element of the deque and returns null in case the deque
is empty.

12.5 THE COLLECTION CLASSES


The collection framework provides various abstract and non-abstract classes that implement collection
interfaces.
The standard collection classes are listed in Table 7:

Table 7: Collection Classes

Class Does this


AbstractCollection It implements the Collection interface..
AbstractList It extends AbstractCollection and implements the List interface.
AbstractQueue It extends AbstractCollection and implements parts of the Queue interface.
AbstractSequentialList It extends AbstractList into a sequential (not random access) list.
LinkedList It extends AbstractSequentialList into a linked list, where each element
knows where the next element is.
ArrayList It implements a dynamic (resizable) array.
ArrayDeque It implements a dynamic double-ended queue by extending AbstractCollection
and implementing the Deque interface (added by Java SE 6).
AbstractSet It extends AbstractCollection and implements the Set interface.
EnumSet It extends AbstractSet to use enum elements.
HashSet It extends AbstractSet to be used with a hash.
LinkedHashSet It extends HashSet and allows insertion-order iterations.
PriorityQueue It extends AbstractQueue to support a priority-based queue.
TreeSet It extends AbstractSet to implement a set stored in tree form.

Let’s explore some commonly used classes in more details.

12.5.1 The AbstractCollection Class


The AbstractCollection class is the implementation of the Collection interface upon which many
Java collection classes are built, so we will take a look at AbstractCollection for reference. Here’s the
inheritance diagram for this class:
java.lang.Object
| java.util.AbstractCollection

9
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

You will find the constructor for the AbstractCollection class in Table 8 and its methods in Table 9:

Table 8: The constructor of the AbstractCollection class

Constructor Does this


protected AbstractCollection() It constructs an AbstractCollection object.

Table 9: Methods of the AbstractCollection class

Method Does this


boolean add(E e) It ensures that this collection contains the given element.
boolean addAll(Collection<? extends It adds all the elements in the given collection to this collection.
E> c)
void clear() It removes all the elements from this collection.
boolean contains(Object o) It returns True if this collection contains the given element.
boolean containsAll It returns True if this collection contains all the elements in the given
(Collection<?> c) collection.

boolean isEmpty() It returns True if this collection contains no elements.


abstract Iterator iterator() It gets an iterator over the elements contained in this collection.
boolean remove(Object o) It removes the given element from this collection.
boolean removeAll It removes all of this collection’s elements that are also contained in the
(Collection<?> c) given collection.

boolean retainAll (Collection<?> c) It keeps only the elements contained in the given collection.
abstract int size() It gets the number of elements in this collection.
Object[] toArray() It gets an array containing all the elements in this collection.
<T> T[] toArray(T[ ] a) It gets an array that contains all the elements in this collection.
String toString() It gets a string representation of this collection.

12.5.2 The AbstractList Class


The AbstractList class extends the AbstractCollection class. It is the foundation of other classes, such as
ArrayList, which supports dynamic arrays. Therefore, we will refer AbstractList here for reference. The
inheritance diagram for this class is as follows:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
You will find the field of the AbstractList class in Table 10, its constructor in Table 11, and its methods in
Table 12:

Table 10: The field of the AbstractList class

Field Does this


protected int modCount It indicates the number of times this list has been modified.

10
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Table 11: The constructor of the AbstractList class

Constructor Does this


protected AbstractList() It constructs an AbstractList object.

Table 12: Methods of the AbstractList class

Method Does this


void add It inserts the given element into this list.
(int index, E element)
boolean add(E e) It adds the given element to the end of this list.
boolean addAll It inserts the elements in the given collection into this list.
(int index, Collection<? extends E> c)
void clear() It removes all the elements from this list.
boolean equals(Object o) It compares the given object with this list for equality.
abstract Object get It gets the element at the given position in this list.
(int index)
int hashCode() It gets the hashcode value for this list.
int indexOf(Object o) It gets the index of the first occurrence of the given element in this list, or
-1 if this list does not contain the element.
Iterator iterator() It gets an iterator over the elements in this list in proper sequence.
int lastIndexOf(Object o) It gets the index of the last occurrence of the given element in this list, or
-1 if this list does not contain the element.
ListIterator listIterator() It gets a list iterator over the elements in this list (in proper sequence).
ListIterator listIterator It gets a list iterator of the elements in this list (in proper sequence),
(int index) starting at the given position in this list.

E remove(int index) It removes the element at the given position in this list.
protected void removeRange It removes from this list all the elements whose index is between fromIndex
(int fromIndex, int and toIndex.

toIndex)
E set(int index, E element) It replaces the element at the given position in this list with the new
element.
List subList(int fromIndex, int It gets a view of the portion of this list between the specified fromIndex
toIndex) (inclusive) and toIndex (exclusive).

12.5.3 The AbstractSequentialList Class


The AbstractSequentialList class is derived from the AbstractList class. It is the foundation of classes,
such as LinkedList. Let’s look at the inheritance diagram for the AbstractSequentialList class:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
| java.util.AbstractSequentialList

11
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

You will find the constructor of the AbstractSequentialList class in Table 13 and its methods in Table 14:

Table 13: The constructor of the AbstractSequentialList class

Constructor Does this


protected AbstractSequentialList() It constructs an AbstractSequentialList object.

Table 14: Methods of the AbstractSequentialList class

Method Does this


void add It inserts the given element at the given position in this list (optional
(int index, E element) operation).

boolean addAll(int index, Collection<? It inserts all the elements in the given collection into this list at the
extends E> c) specified position (optional operation).
Object get(int index) It gets the element at the given position in this list.
Iterator<E> iterator() It gets an iterator over the elements in this list.
abstract ListIterator<E> It gets a list iterator over the elements in this list.
listIterator(int index)
E remove(int index) It removes the element at the given position in this list (optional
operation).
E set It replaces the element at the given position in this list with the
(int index, E element) specified element (optional operation).

12.5.4 The ArrayList Class


The ArrayList class is an array class that can grow or shrink at runtime. Note that arrays of this class
must hold objects, not just simple data types. Here’s the inheritance diagram for this class:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
| java.util.ArrayList
You will find the constructors of the ArrayList class in Table 15 and its methods in Table 16:

Table 15: Constructors of the ArrayList class

Constructor Does this


ArrayList() It constructs an ArrayList object.
ArrayList (Collection<? extends E> c) It constructs a list containing the elements of the given collection.
ArrayList(int initialCapacity) It constructs an empty list with the given initial capacity.

Table 16: Methods of the ArrayList class

Method Does this


void add(int index, E element) It inserts the given element at the given position in this list.
boolean add(E e) It adds the given element to the end of this list.

12
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


boolean addAll It adds all the elements in the given collection to the end of this list in
(Collection<? extends E> c) the order that they are returned by the specified collection’s Iterator.

boolean addAll It inserts all the elements in the given collection into this list, starting
(int index, Collection<? extends E> c) at the given position.

void clear() It removes all the elements from this list.


Object clone() It gets a copy of this ArrayList instance.
boolean contains It returns True if this list contains the given element.
(Object elem)
void ensureCapacity It increases the capacity of this ArrayList instance.
(int minCapacity)
void forEach(Consumer<? super E> It performs the given action for each element of the Iterable until all
action) elements have been processed or the action throws an exception.
Object get(int index) It gets the element at the given position in this list.
int indexOf(Object elem) It returns the index of the first occurrence of the given element in this
list, or -1 if this list does not contain the element.
boolean isEmpty() It returns true if this list has no elements.
int lastIndexOf It gets the index of the last occurrence of the given element in this list,
(Object elem) or -1 if this list has no element.

E remove(int index) It removes the element at the given position in this list.
boolean remove(Object elem) It removes the first occurrence of the specified element from this list,
if it is present.
protected void removeRange It removes from this list all the elements whose index is between
(int fromIndex, int toIndex) fromIndex and toIndex.

E set(int index, E element) It replaces the element at the given position in this list with the given
element.
int size() It gets the number of elements in this list.
void sort(Comparator<? super E> c) It sorts this list according to the order induced by the specified
Comparator.
Spliterator<E> spliterator() It creates a late-binding and fail-fast Spliterator over the elements in
this list.
List<E> subList(int fromIndex, int It returns a view of the portion of this list between the specified
toIndex) fromIndex, inclusive and toIndex, exclusive.
Object[] toArray() It gets an array containing all the elements in this list in proper
sequence(from first to last element).
<T> T[] toArray(T[] a) It gets an array containing all the elements in this list in proper
sequence(from first to last element); the runtime type of the returned
array is that of the specified array.
void trimToSize() It trims the capacity to be the list’s current size.

You can add elements to an ArrayList object with the add() method, get an element at a certain index
with the get() method, and remove elements with the remove() method. Let’s consider an example in

13
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

which we add elements to an array at runtime. Remember, we are using two forms of the add() method:
general form and the form that allows to add an element at a specific location(index). We are also using
the remove() method to remove one element. The Iterator interface is defined in the java.util package.
This Iterator interface has three methods—hasNext(), next() and remove(). These methods are all you
need to access each element of a collection, as you see in Program 1:
Program 1: Using the ArrayList Class
import java.util.*;
class Arraylist
{
public static void main(String args[])
{
ArrayList<String> arraylist = new ArrayList<String>();
arraylist.add("C++");
arraylist.add("C#");
arraylist.add("JavaScript ");
arraylist.add("Python ");
arraylist.add("VB");
arraylist.add("R");
arraylist.add(1, "Java");

System.out.println("\nUsing the add method");


System.out.println(arraylist);

arraylist.remove("VB");

System.out.println(arraylist);
System.out.println("\nUsing the Iterator interface");
String s;
Iterator e = arraylist.iterator();
while (e.hasNext())
{
s = (String)e.next();
System.out.println(s);
}
}
}
Here’s the output of Program:
D:\Java folder\java Arraylist
Using the add method
[C++, Java,C#, JavaScript, Python, VB, R]
[C++, Java,C#, JavaScript, Python, R]

Using the Iterator interface


C++
Java
C#
JavaScript

14
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Python
R

12.5.5 The ArrayDeque Class


The ArrayDeque class was added in Java SE 6. It extends AbstractCollection and implements the Deque
interface. It does not add methods on its own. The ArrayDeque class forms a dynamic array which has
no limitations on capacity. The Deque interface supports implementation that limits capacity, but does
not require such restrictions.
The ArrayDeque class is a generic class and its inheritance diagram is as follows:
java.lang.Object
| java.util.AbstractCollection
| java.util.ArrayDeque
You will find the constructors of the ArrayDeque class in Table 17 and its methods in Table 18:

Table 17: Constructors of the ArrayDeque class

Constructor Does this


ArrayDeque() It constructs an ArrayDeque object.
ArrayDeque(Collection<? extends E> c) It constructs a deque containing the elements of the given
collection.
ArrayDeque(int numElements) It constructs an empty deque with the given initial capacity.

Table 18: Methods of the ArrayDeque class

Method Does this


boolean add(E e) It adds the given element to the end of this deque.
void addFirst(E e) It adds the given element to the front of this deque.
void addLast (E e) It inserts the given element at the end of this deque.
void clear() It removes all the elements from this deque.
ArrayDeque<E> clone() It gets a copy of this ArrayDeque instance.
boolean contains (Object elem) It returns True if this deque contains the given element.
Iterator<E> descendingIterator() It returns an iterator over the elements in this deque in reverse
sequential order.
E element() It retrieves, but does not remove, the head of the queue represented
by this deque.
E getFirst() It retrieves, but does not remove, the first elements of this deque.
E getLast() It retrieves, but does not remove, the last elements of this deque.
boolean isEmpty() It returns true if this deque has no elements.
Iterator<E> iterator() It returns an iterator over the elements in this deque.
boolean offer(E e) It inserts the specified element at the end of this deque.
boolean offerFirst(E e) It inserts the specified element at the front of this deque.
boolean offerLast(E e) It inserts the specified element at the end of this deque.

15
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


E peek() It retrieves, but does not remove, the head of the queue represented
by this deque, or return null if this deque is empty.
E peekFirst() It retrieves, but does not remove, the first element of this deque, or
return null if this deque is empty.
E peekLast() It retrieves, but does not remove, the last element of this deque, or
return null if this deque is empty.
E poll() It retrieves and removes, the head of the queue represented by this
deque, or return null if this deque is empty.
E pollFirst() It retrieves and removes the first element of this deque or return
null if this deque is empty.
E pollLast() It retrieves and removes the last element of this deque or return
null if this deque is empty.
E pop() It pops an element from the stack represented by this deque.
void push(E e) It pushes an element from the stack represented by this deque.
E remove() It retrieves and removes the head of the queue represented by this
deque.
E removeFirst() It retrieves and removes the first element of this deque.
E removeLast() It retrieves and removes the last element of this deque.
boolean removeFirstOccurrence It removes the last occurrence of the specified element in this deque.
(Object o)
int size() It returns the number of elements in this deque.
Spliterator<E> spliterator() It creates a late-binding and fail-fast Spliterator over the elements
in this deque.
Object toArray() It returns an array containing all of the elements in this deque in
proper sequence(from first to last element).
<T> T[] toArray(T[] a) It returns an array containing all of the elements in this deque in
proper sequence(from first to last element); the runtime type of the
returned array is that of the specified array.

To build a linked list, you can use the add(), addFirst() and addLast() methods; to get an element at a
certain index, you can use the get(), getFirst() and getLast() methods; to set an element’s value, you can
use the set method; and to remove an element, you can use the remove(), removeFirst() and removeLast()
methods.
Program 2 demonstrates ArrayDeque by using it to create a stack:
Program 2: Using the ArrayDeque Class
import java.util.*;
class ArrayDequeDemo { public static void main(String args[])
{
ArrayDeque<String> arrdeque= new ArrayDeque<String>();
arrdeque.push("C++"); arrdeque.push("C#");
arrdeque.push("JavaScript");
arrdeque.push("VB");

16
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

arrdeque.push("VB");
arrdeque.push("R");
System.out.println("Popping the stack: ");
while (arrdeque.peek() != null)
{
System.out.println(arrdeque.pop() + " ");
}
System.out.println();
}
}
Here's the output of Program:
D:\Java folder\java ArrayDequeDemo
Popping the stack:
R
VB
Python
JavaScript
C#
C++

12.5.6 The LinkedList Class


The LinkedList class supports linked lists in which a record of items is maintained in these lists. With the
use of such a list, you can move one element to the next using an iterator. The inheritance diagram for
the LinkedList class is as follows:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
| java.util.AbstractSequentialList
| java.util.LinkedList
You will find the constructors of the LinkedList class in Table 19 and its methods in Table 20:

Table 19: Constructors of the LinkedList class

Constructor Does this


LinkedList() It constructs a LinkedList object.
LinkedList(Collection<? extends E> c) It constructs a list containing the elements of the given collection.

Table 20: Methods of the LinkedList class

Method Does this


void add(int index, E element) It inserts the given element at the given position.
boolean add(E e) It adds the given element to the end of this list.
boolean addAll (Collection<? extends It adds all the elements in the given collection to the end of this list.
E> c)
boolean addAll(int index, It inserts all the elements in the given collection into this list.
Collection<? extends E> c)

17
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


void addFirst(E e) It inserts the specified element at the beginning of this list.
void addLast(E e) It adds the specified element to the end of this list.
void clear() It removes all the elements from this list.
Object clone() It gets a copy of this LinkedList object.
boolean contains(Object o) It returns True if this list contains the given element.
Iterator<E> descendingIterator() It gets an iterator over the elements in this deque in reverse sequential
order.
E element() It gets, but does not remove, the head (first element) of this list.
E get(int index) It gets the element at the given position in this list.
E getFirst() It gets the first element in this list.
E getLast() It gets the last element in this list.
int indexOf(Object o) It gets the index of the first occurrence of the specified element in this
list, or -1 if this list does not contain the element.
int lastIndexOf(Object o) It gets the index of the last occurrence of the specified element in this list
or -1, if this list does not contain the element.
ListIterator<E> listIterator(int index) It gets a list iterator of the elements in this list, starting at the given
position in the list.
boolean offer(E e) It appends the specified elements as the tail (last element) of this list.
boolean offerFirst It inserts the specified element at the front of this list.
(E e)
boolean offerLast(E e) It inserts the specified element at the end of this list.
E peak() It gets the element, but does not remove, the head (first element) of this
list.
E peakFirst() It gets the element, but does not remove, the first element of this list, or
returns null if this list is empty.
E peakLast() It gets the element, but does not remove, the last element of this list, or
returns null if this list is empty.
E poll() It gets and removes the head (first element) of this list.
E pollFirst() It gets and removes the first element of this list, or returns null if this list
is empty.
E pollLast() It gets and remove the last element of this list or returns null if this list
is empty.
E pop() It pops an element from the stack represented by this list.
void push(E e) It pushes an element onto the stack represented by this list.
E remove(int index) It removes the element at the given position in this list.
boolean remove(Object o) It removes the first occurrence of the given element in this list.
E removeFirst() It removes and returns the first element from this list.
boolean removeFirstOccurrence It removes the first occurrence of the specified element in this list.
(Object e)

18
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


E removeLast() It removes and returns the last element from this list.
boolean It removes the last occurrence of the specified element in this list.
removeLastOccurrence(Object e)
E set(int index, E element) It replaces the element at the given position in this list with the given
element.
int size() It gets the number of elements in this list.
Spliterator<E> HYPERLINK “http:// It creates a late-binding and fail-fast Spliterator over the elements in
docs.oracle.com/javase/8/docs/ this list.
api/java/util/LinkedList.html” \l
“spliterator--” spliterator()
Object[] toArray() It gets an array containing all the elements in this list in the correct
order.
<T> T[] toArray (T[] a) It gets an array containing all the elements in this list in the correct
order.

To build a linked list, you can use the add(), addFirst() and addLast() methods; to get an element at a
certain index, you can use the get(), getFirst() and getLast() methods; to set an element’s value, you
can use the set() method; and to remove an element, you can use the remove(), removeFirst(), and
removeLast() methods.

12.5.7 The HashSet Class


A set is defined as a group of unique elements, and the HashSet class supports sets that use a hash
internally for storage. Because this class uses a hash internally, methods, such as contains(), remove(),
add() and size(), always take the same amount of time to execute. The inheritance diagram for this class
is as follows:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractSet
| java.util.HashSet
You will find the constructors of the HashSet class in Table 21 and its methods in Table 22:

Table 21: Constructors of the HashSet class

Constructor Does this


HashSet() It constructs a new, empty set.
HashSet(Collection<? extends E> c) It constructs a new set containing the elements in the given collection.
HashSet(int initialCapacity) It constructs a new, empty set with the given initial capacity and
default load factor (0.75).
HashSet (int initialCapacity, float It constructs a new, empty set with the given initial capacity and the
loadFactor) given load factor.

Table 22: Methods of the HashSet class

Method Does this


boolean add(E e) It adds the given element to this set if it’s not already present.

19
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


void clear() It removes all the elements from this set.
Object clone() It gets a copy of this HashSet instance.
boolean contains(Object o) It returns True if this set contains the given element.
boolean isEmpty() It returns True if this set contains no elements.
Iterator<E> iterator() It gets an iterator over the elements in this set.
boolean remove(Object o) It removes the given element from this set if it’s present.
int size() It gets the number of elements in this set.
Spliterator<E> spliterator() It creates a late-binding and fail-fast Spliterator over the elements in
this set.

Program 3 shows an example of HasSet in which we add elements to a set and then print out that set:
Program 3: Using the HashSet Class
import java.util.*;

class Hashset
{
public static void main(String args[])
{
HashSet<String> hashset1 = new HashSet<String>();
hashset1.add("C++");
hashset1.add("Java");
hashset1.add("C#");
hashset1.add("JavaScript");
hashset1.add("Python");
hashset1.add("VB");
hashset1.add("R");
System.out.println(hashset1);
}
}
Here’s the output of Program:
D:\Java folder\java Hashset
[C++, Python, JavaScript, C#, Java, R, VB]
One thing to note about hashes is that you can’t guarantee the order in which elements are stored
internally. In fact, when you print out this set, you can see that all elements are stored in exactly the
reverse order:

12.5.8 The TreeSet Class


The TreeSet class uses a tree to construct for internal storage to implement a set, which means that
access times are fast. The elements of the TreeSet class are stored in a sorted order and its inheritance
diagram is as follows:
java.lang.Object
| java.util.AbstractCollection

20
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

| java.util.AbstractSet
| java.util.TreeSet
You will find the constructors for the TreeSet class in Table 23 and its methods in Table 24:

Table 23: Constructors of the TreeSet class

Constructor Does this


TreeSet() It constructs a new, empty tree set, sorting according to the natural
ordering of its elements.
TreeSet (Collection<? extends E> c) It constructs a new tree set containing the elements in the given
collection, sorting according to the natural ordering of its elements.
TreeSet (Comparator<? super E> It constructs a new, empty tree set, sorted according to the given
comparator) comparator.
TreeSet (SortedSet<E> s) It constructs a new tree set containing the same elements and using
the same ordering as the given sorted set.

Table 24: Methods of the TreeSet class

Method Does this


boolean add(E e) It adds the given element to this set.
boolean addAll It adds all the elements in the given collection.
(Collection<? extends E> c)
E ceiling(E e) It returns the least element in this set greater than or equal to the
given element, or null if there is no such element.
void clear() It removes all the elements from this set.
Object clone() It gets a shallow copy of this TreeSet instance.
Comparator <? super E> comparator() It gets the comparator used to order the element in this set or null if
this set uses the natural ordering.
boolean contains(Object o) It returns True if this set contains the given element.
Iterator<E> descendingIterator() It returns an iterator over the elements in this set in descending
order.
NavigableSet<E> descendingSet() It returns a reverse order view of the elements contained in this set.
E first() It gets the first (lowest) element currently in this set.
E floor(E e) It gets the greatest element in this set less than or equal to the given
element, or null if there is no such element.
SortedSet<E> headset(E e) Equivalent to navigableHeadSet (Object e) SortedSet interface.
NavigableSet<E> headSet(E toElement, It returns a view of the portion of this set whose elements are less
boolean inclusive) than (or equal to, if inclusive is true) toElement.
E higher(E e) It returns the least element in this set, which is greater than the
given element, or null if there is no such element.
boolean isEmpty() It returns True if this set contains no elements.
Iterator<E> iterator() It gets an iterator over the elements in this set in ascending order.
E last() It gets the last (highest) element currently in this set.

21
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


E lower(E e) It returns the greatest element in this set strictly less than the given
element, or null if there is no such element.
NavigableSet<E> subSet(E fromElement, It returns a view of the portion of this set whose elements range
boolean fromInclusive, E toElement, from fromElement to toElement.
boolean toInclusive)
SortedSet<E> subSet(E fromElement, E It returns a view of the portion of this set whose elements range
toElement) from fromElement, inclusive, to toElement, exclusive.
SortedSet<E> tailSet(E fromElement) It returns a view of the portion of this set whose elements are greater
than or equal to fromElement.
NavigableSet<E> tailSet(E fromElement, It returns a view of the portion of this set whose elements are greater
boolean inclusive) than (or equal to, if inclusive is true) fromElement.
E pollFirst() It gets and removes the first element, or returns null if this set is
empty.
E pollLast() It gets and removes the last element, or returns null if this set is
empty.
boolean remove(E e) It removes the given element from this set if it’s present.
int size() It gets the number of elements in this set.

The TreeSet class just implements a set using a tree for internal storage. A difference from the HashSet
class is that elements in a TreeSet object are stored in sorted order.

12.6 ACCESSING A COLLECTION VIA AN ITERATOR


Sometimes you need to traverse the elements of a collection for some specific purpose, for instance,
to display each element. To implement this, you need an iterator either using the Iterator interface or
using the ListIterator interface. The Iterator interface enables traversing a collection, by obtaining
or removing elements. The ListIterator interface extends the Iterator interface to allow bidirectional
traversal of a list, and the modification of elements. Iterator and ListIterator are generic interfaces
which are declared as shown here:
interface Iterator<E> interface ListIterator<E>
Here, E specifies the type of objects being iterated.

12.6.1 Using the Iterator Interface


The methods of the Iterator interface can be used to move through an accumulation using the next()
method, allowing you to cycle through the elements of the collection. The methods of the Iterator
interface are shown in Table 25:

Table 25: Methods of the Iterator interface

Method Does this


boolean hasNext() It returns True if the iteration has more elements.
Object next() It gets the next element in the iteration.
void remove() It removes the last element returned.

22
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

12.6.2 Using the ListIterator Interface


Whereas iterators can only work forward through a list using the next() method, list iterators also
support the previous() method, so they can work backwards through lists. This is particularly useful
for linked lists, where each element often must know about the next and previous elements (called a
bidirectional linked list). This is handy, for example, when you are implementing a buffer that can grow
or shrink. You will find the methods of the ListIterator interface in Table 26:

Table 26: Methods of the ListIterator interface

Method Does this


void add(E e) It inserts the given element into the list.
boolean hasNext() It returns True if this list iterator has more elements in the forward direction.
boolean hasPrevious() It returns True if this list iterator has more elements in the reverse direction.
E next() It gets the next element in the list.
int nextIndex() It gets the index of the element that would be returned by a subsequent call
to next().
E previous() It gets the previous element in the list.
int previousIndex() It gets the index of the element that would be returned by a subsequent call
to previous.
void remove() It removes from the list the last element that was returned by next or previous.
void set(E e) It replaces the last element returned by next or previous with the given
element.

12.7 STORING USER-DEFINED CLASSES IN COLLECTIONS


In this section, you will learn that collections store not only built-in objects, such as String or Integer; but
also objects of user defined classes. Program 4 shows how a LinkedList store student records:
Program 4: Storing Objects of User-Defined Classes
import java.util.*;
class StudentRecords {
private String name;
private String roll;
private String address;
private String state;
private String marks;
StudentRecords(String nm, String r, String ad, String st, String mk) {
name = nm;
roll = r;
address = ad;
state = st;
marks = mk;
}
public String toString() { return name + "\n" + roll + "\n" + address + "
" + state + " " + marks;
}
}

23
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

public class Detail {


public static void main(String args[]) {
LinkedList<StudentRecords> sr = new LinkedList<StudentRecords>();
sr.add(new StudentRecords("Rahul", "101238","A/45, Thana", "Mumbai",
"1801"));
sr.add(new StudentRecords("Yogita", "105638","6-78, Saharanpur", "Delhi",
"1853"));
sr.add(new StudentRecords("Rajni", "101264","Sector 9, Chandigarh",
"Punjab", "1820"));
for(StudentRecords element : sr)
System.out.println(element + "\n");
System.out.println();
}
}
Output of Program 4:
Rahul
101238
A/45, Thana Mumbai 1801

Yogita
105638
6-78, Saharanpur Delhi 1853

Rajni
101264
Sector 9, Chandigarh Punjab 1820

12.8 THE RANDOM ACCESS INTERFACE


RandomAccess is an empty interface or called a marker interface. All these marker interfaces do
not define methods. The RandomAccess interface provides fast random access to java.util.List
implementation. According to Java documentation, a List implementation should implement this
interface if the following loop:
for (int i=0, n=list.size(); i < n; i++)
list.get(i);
runs faster than the following loop:
for (Iterator i=list.iterator(); i.hasNext(); )
i.next();
In the client code, you can check whether the collection is an instance of RandomAccess, and then only
perform the Random access operations, as shown in the following code snippet:
Collection<Integer> col = new ArrayList<Integer>();
if (col instanceof RandomAccess){
System.out.println("Use random access process");
}
else{
System.out.println(Use sequential process");
}

24
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

12.9 WORKING WITH MAPS


You can also use the maps in Java. A map is an object that stores associations between keys and values
in pairs. It stores data in key/value pairs, much like an array, where the indexes are, themselves, objects.
Typically, keys are strings, and you can look up an object in a map by using that object. Both keys and
values are objects. The keys must be unique, but the values may be duplicated. Some maps can also
accept a null key and null values. Note that maps don›t implement the Iterable interface. It means that
you cannot iterate map elements using iterator.

12.9.1 The Map Interfaces


The Map interface maps a unique key to a specific value and that key is used to retrieve a value. In other
words, you can store a value in a Map object and later retrieve the value from a Map object using a
unique key. By implementing the Map interface to your class, the following operations can be performed:
 Locate a value on the basis of a key
 Retrieve all values of a collection
 Retrieve all keys of a collection

Here are the map interfaces:


 Map: It implements a map.
 Map.Entry: The inner class of Map that describes a key/value pair in a map.
 NavigableMap: It extends SortedMap to handle the retrieval of entries based on closest match
searches (added by Java SE 6).
 SortedMap: It extends Map to keep the keys in ascending order.

Similar to the Sets and Lists interfaces, the Maps also use the equals() method to verify whether two keys
are the same or not.
Java also derives some standard classes from these interfaces—the map classes.

12.9.2 The Map Classes


Here are the standard map classes defined by Java:
 AbstractMap: It implements the Map interface.
 HashMap: It extends AbstractMap using a hash.
 TreeMap: It extends AbstractMap using a tree.
 WeakHashMap: It extends AbstractMap using a hash with weak keys, which means that elements
whose keys are no longer in use will be discarded.

You will also see other classes here that are not technically members of the collection framework—
Arrays, Vector, Stack, Hashtable and others. These older collections have been rebuilt on collection
framework functionality. In fact, most standard computing collections are implemented in Java in
various ways; for example, the TreeSet class implements a set using a tree internally, which means
access time is quick. HashSet implements a set using a hash internally, which means that adding and
removing elements from such a set should always take the same amount of time, no matter how large
the set grows.

25
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Using the AbstractMap Class


The AbstractMap class is the base of the map classes in Java, so we will give a quick glance to refer it.
The inheritance diagram for the AbstractMap class is as follows:
java.lang.Object
| java.util.AbstractMap
You will find the constructor of the AbstractMap class in Table 27 and its methods in Table 28:

Table 27: The constructor of the AbstractMap class

Constructor Does this


protected AbstractMap() It constructs an AbstractMap object.

Table 28: Methods of the AbstractMap class

Method Does this


void clear() It removes all mappings.
boolean containsKey It returns True if this map contains a mapping for the given key.
(Object key)
boolean containsValue It returns True if this map maps one or more keys to the specified.
(Object value)
abstract Set<Map.Entry<K,V>> It returns a Set.
entrySet()
boolean equals(Object o) It compares the given object with this map for equality.
V get(Object key) It gets the value to which the specified key is mapped or null if this map
contains no mapping for the given key.
int hashCode() It gets the hashcode value for this map.
boolean isEmpty() It returns True if this map contains no key/value mappings.
Set<K> keySet() It returns a Set.
V put(K key, V value) It associates the given value with the given key in this map.
void putAll(Map<? extends K,? It copies all the mappings from the given map to this map.
extends V> m)
Object remove(Object key) It removes the mapping for a key from this map, if it is present.
int size() It gets the number of key/value mappings in this map.
String toString() It gets a string representation of this map.
Collection<V> values() It returns a Collection.

Using the HashMap Class


Maps make it possible to store data as key/value pairs, where both the key and the values are the objects.
For example, creation of a map indexed with strings and not numbers. The inheritance diagram for the
HashMap class is as follows:
java.lang.Object
| java.util.AbstractMap
| java.util.HashMap

26
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

You will find the constructors for the HashMap class in Table 29 and its methods in Table 30:

Table 29: Constructors of the HashMap class

Constructor Does this


HashMap() It constructs a new, empty map.
HashMap(int initialCapacity) It constructs a new, empty map with the given initial capacity.
HashMap(int initialCapacity, float It constructs a new, empty map with the given initial capacity and the
loadFactor) given load factor.
HashMap (Map<? extends K,? It constructs a new map with the same mappings as the given map.
extends V> m)

Table 30: Methods of the HashMap class

Method Does this


void clear() It removes all of the mappings from this map.
Object clone() It gets a copy of this HashMap instance.
boolean containsKey (Object key) It returns True if this map contains a mapping for the given key.
boolean containsValue It returns True if this map maps one or more keys to the given value.
(Object value)
Set<Map.Entry<K,V>> entrySet() It returns a Set.
void forEach(BiConsumer<? super It performs the given action for each entry in this map until all entries
K,? super V> action) have been processed or the action throws an exception.
V get(Object key) It gets the value to which the given key is mapped, or null if this map
contains no mapping for the key.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped or defaultValue if
defaultValue) this map contains no mapping for the key.
boolean isEmpty() It returns True if this map contains no key/value mappings.
Set<K> keySet() It returns a Set.
V put(K key, V value) It associates the given value with the given key in this map.
void putAll (Map<? extends K,? It copies all the mappings from the given map to this map.
extends V> m)
V remove(Object key) It removes the mapping for the specified key from this map if present.
boolean remove(Object key, Object It removes the entry for the specified key only if it is currently mapped to
value) the specified value.
boolean replace(K key, V oldValue, V It replaces the entry for the specified key only if currently mapped to the
newValue) specified value.
void replaceAll(BiFunction<? super It replaces each entry’s value with the result of invoking the given function
K,? super V,? extends V> function) on that entry until all entries have been processed or the function throws
an exception.
int size() It gets the number of key/value mappings in this map.
Collection<V> values() It gets a Collection.

27
JGI JAIN DEEMED-TO-BE UNIVERSIT Y
Java Programming

The put() method is used to add a key/value pair to a map, and the get() method is used to retrieve
a value, given a key. For example, the string drink will be left holding the text “root beer” after this
example executes:
hashmap.put("drink", "root beer");
String drink = hashmap.get("drink");
You can also get a set corresponding to the map with the entrySet() method, and you can iterate over
that set using the Map.Entry interface.

Using the TreeMap Class


The TreeMap class executes a map with the use of a tree internally to store data. The inheritance diagram
for this class is as follows:
java.lang.Object
| java.util.AbstractMap
| java.util.TreeMap
You will find the constructors for the TreeMap class in Table 31 and its methods in Table 32:

Table 31: Constructors of the TreeMap class

Constructor Does this


TreeMap() It constructs a new, empty tree map, using natural ordering of its keys.
TreeMap(Comparator<? super K> It constructs a new, empty tree map, ordered according to the given
comparator) comparator.
TreeMap(Map<? extends K,? extends It constructs a new tree map containing the same mappings as the given
V> m) map, ordered according to the natural ordering of its keys.
TreeMap(SortedMap<K,? extends It constructs a new tree map containing the same mappings and using the
V> m) same ordering as the given sorted map.

Table 32: Methods of the TreeMap class

Method Does this


Map.Entry(K,V) ceilingEntry It returns a key-value mapping associated with the least key greater than
(K key) or equal to the given key, or null if there is no such key.

K ceilingKey It returns the least key greater than or equal to the given key, or null if
(K key) there is no such key.

void clear() It removes all of the mappings from this map.


Object clone() It gets a copy of this TreeMap instance.
Comparator <? super K> It gets the comparator used to order the keys in this map, or null if this
comparator() map uses the natural ordering.
boolean containsKey It returns True if this map contains a mapping for the specified key.
(Object key)
boolean containsValue It returns True if this map maps one or more keys to the specified value.
(Object value)

28
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


NavigableSet<K> It returns a reverse order NavigableSet view of the keys contained in this
descendingKeySet() map.
NavigableMap<K,V> It returns a reverse order view of the mappings contained in this map.
descendingMap()
Set<Map.Entry<K,V>> entrySet() It returns a Set.
Map.Entry<K,V> firstEntry() It returns a key-value mapping associated with the least key in this map,
or null if the map is empty.
K firstKey() It returns the first (lowest) key currently in this map.
Map.Entry<K,V> floorEntry(K key) It returns a key-value mapping associated with the greatest key less than
or equal to the given key, or null if there is no such key.
K floorKey(Object key) It returns the greatest key less than or equal to the given key, or null if
there is no such key.
void forEach(BiConsumer<? super It performs the given action for each entry in this map until all entries
K,? super V> action) have been processed or the action throws an exception.
V get(Object key) It gets the value to which the specified key is mapped, or null if this map
contains no mapping for the key.
SortedMap <K,V> headMap Equivalent to navigableHeadMap (Object toKey) SortedMap interface.
(K toKey)
Map.Entry <K,V> higherEntry(K It returns a key-value mapping associated with the least key strictly
key) greater than the given key or null if there is no such key.
K higherKey(K key) It returns the least key strictly greater than the given key or null if there
is no such key.
Set<K> keySet() It returns a Set.
Map.Entry<K,V> lastEntry() It returns a key-value mapping associated with the greatest key in this
map, or null if the map is empty.

12.10 COMPARATORS
You can use a comparator to find the sorting order used in the TreeSet objects; for example, with the
implementation of the Comparator interface. The methods of this interface are provided in Table 33:

Table 33: Methods of the Comparator interface

Method Does this


int compare(Object obj1, It compares its two arguments.
Object obj2)
boolean equals(Object obj) It specifies whether another object is equal to this comparator.

The compare() method compares two objects, obj1 and obj2, and returns -1 if obj1 is less than obj2; 0 if
they are equal; and 1 if obj1 is greater than obj2. By overriding this method, you can support a custom
sorting order.
Consider Program 5 in which we sort a TreeSet object in ascending order—except for one element,
JavaScript, which we always want to appear at the beginning of the set.

29
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Program 5: Sorting a TreeSet object in ascending order


import java.util.*;

class ComparatorDemo
{
@SuppressWarnings("unchecked")
public static void main(String args[])
{
TreeSet<String> treeset = new TreeSet<String>(new
NewComparator());
treeset.add("C++");
treeset.add("Java");
treeset.add("C#");
treeset.add("JavaScript");
treeset.add("Python");
treeset.add("VB");
treeset.add("R");
Iterator iterator = treeset.iterator();
while(iterator.hasNext()) { System.out.println(iterator.
next()); }
}
}
class NewComparator implements Comparator {
public int compare(Object obj1, Object obj2) {
if (((String) obj1).equals("JavaScript")) return -1;
return ((String) obj1).compareTo((String) obj2); }
}
Here’s the output of this example. Note that item at index 3 i.e.‘JavaScript’ comes first:
D:\Java folder\java ComparatorDemo
JavaScript
C++
Java
C#
Python
VB
R

12.11 THE COLLECTIONS ALGORITHMS


The collections framework allows you to provide various high-performance algorithms for handling
collection elements. These algorithms are generally implemented as static methods of class Collections.
The algorithms, such as binarySearch, sort, shuffle, reverse, fill and copy, are used with Lists. On the
other hand, algorithms, such as min, max, addAll, frequency and disjoint works with Collections. The
descriptions of various algorithms are as follows:
 sort: Allows you to sort the elements of a list
 binarySearch: Allows you to locate an object in a list
 reverse: Allows you to reverse the elements of a list

30
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

 shuffle: Allows you to randomly orders a elements of a list


 fill: Allows you to set every list element to refer to a declared object
 copy: Allows you to copy references from one list into another
 min: Allows you to return the smallest element specified in a collection
 max: Allows you to return the largest element in a collection
 addAll: Allows you to append all elements in an array to a collection
 frequency: Allows you to calculate how many elements in the collection are equal to the specified
element
 disjoint: Allows you to determine whether two collections have no elements in common

The collections framework algorithms are polymorphic which means each algorithm can operate on
objects that implement specific interfaces, irrespective of the basic implementations.

12.12 WHY GENERIC COLLECTIONS?


One important feature of Java programming is that it is type-safe. If you assign a value to a variable of
a different data type without typecasting, the compiler generates an error. For example, if you create an
array of type Integer, then assigning any other type of value in the array except Integer will generate
a compilation error. This feature of Java has some limitations while creating collections. For example,
while creating a collection, any type of object can be assigned to it. When you are accessing the objects
from the collection, you will have to take care of the type of object you are accessing. The following code
snippet shows an example of creating a collection:
List objList=new LinkedList();
objList.add(new Integer(0));
Integer var=(Integer)objList.iterator().next();
In the preceding code snippet, the collection objList of LinkedList type is created. Next, an object of type
Integer is added to the objList collection. The objects of the objList collection are retrieved and assigned
to an object of type Integer. Although an Integer object is added to the objList collection, any type of
object can be added to the collection. As you can notice in the preceding code snippet, the retrieved
object is typecast into the Integer type of object. The most important fact to be noticed is that even
though you added only Integer type of objects to the collection, when you retrieve the objects from
the collection, you need to typecast them. This typecast is necessary because all the objects added to
a collection are implicitly considered as the Object type. This typecasting may cause runtime errors if
a collection contains objects of different data types, as you will not be aware of which type of object is
stored in the collection.

The concept of generics was introduced in JDK 1.5 to overcome the problem of explicit typecasting.
It has also introduced some other exciting features. In the case of generic collection, Java allows the
programmer to create a collection which is type-safe and does not need explicit typecasting while
retrieving the objects from the collection. The following code snippet represents the generic type of
collection creation of the preceding code snippet:
List<Integer> objList=new LinkedList<Integer>();
objList.add(new Integer(0));
Integer var=objList.iterator().next();

31
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

In the preceding code snippet, the collection objList is created with a specified type Integer. According
to the preceding code snippet, Integer is a parameterised type or type parameter. The type parameter
intimates the compiler that the collection objList contains objects of only Integer data type. Now, no
other object type other than of Integer type can be assigned to the collection. An attempt to do this will
generate a compile-time error. In the case of generic collections, the compiler is aware of the type of
objects that are supposed to be added to the collection. Therefore, there is no need to explicitly typecast,
as shown in the preceding code snippet.
Another feature of generic collections is that you can define a method with the type parameter. Passing
the type parameter in a method makes the argument of the method type-safe. For example, the following
code snippet defines a method with the type parameter argument:
void addIntegerList(List<Integer> intobj) {
intobj.add(new Integer(25));
}
In the preceding code snippet, the addIntegerList method is defined with an argument intobj, which is
declared as a type parameter Integer. This parameter is type-safe now. If you try to add any object of
data type other than an Integer, a compile-time error will be generated. Consider the following code
snippet that will generate a compilation error:
void addIntegerList(List<Integer> intobj) {
intobj.add("Vikash");
}
In the preceding code snippet, in place of an Integer object a String object Vikash is added to the collection
intobj. It is illegal and generates a compilation error. The compilation error is generated because the
intobj collection is type-safe and only objects of the Integer type can be added to it.
Similar to the argument of a method, the return type of a method can also be made type-safe by
declaring its return type with type parameter. The following code snippet defines a method with the
type-safe return type:
List<Integer> getIntegerList() {
List<Integer> objList=new LinkedList<Integer>();
return objList;
}
In the preceding code snippet, the getIntegerList() method is defined, which returns a collection of
Integer type of objects. The return type of this method is type-safe. An attempt to return any other type
of collection object from this method will cause a compilation error. The following code snippet defines
a method that will generate a compilation error:
List<Integer> getIntegerList() {
List<String> strList=new ArrayList<String>();
return strList;
}
In the preceding code snippet, instead of returning an Integer type of collection a collection of type
String is returned from the method. This causes a compilation error because the return type of the
method is type-safe and it must return a collection of Integer type of objects only. An advantage of
making the return type of the method type-safe is that when this method is called explicit typecast of
the object to be returned from the method is not required. This is because the compiler is aware of the
type of the collection objects to be returned from the method.

32
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

The collection with which the concept of generic is implemented, that is, the type parameters are used
are called generic collections, whereas the collections created with the legacy style of code are called
non-generic collections. You can create a collection with the type parameter <Object>, which contains
any type of object similar to the non-generic collections. Although a collection with the type parameter
<Object> is similar to non-generic collections, it sometimes behaves differently. You will notice this
difference in the following sections in which generic classes and non-generic classes in the collections
are discussed.

12.13 THE LEGACY CLASSES AND INTERFACES


Talking about earlier versions of Java, legacy classes and interfaces formed the collections framework
and now they are reconstructed in coming versions. With the Java SE 7 release, for legacy file I/O code,
the java.io.File class was the process used for file I/O; however, it has the following demerits:
 Many methods didn’t throw exceptions when they failed, so it was impossible to retrieve a useful
error message.
 The rename method didn’t work properly across platforms.
 There was no real support for symbolic links.
 Needed more support for metadata, such as file permissions, file owner and other security attributes.
 Executing file metadata was inefficient.
 It was impossible to write a reliable code that could iteratively walk a file tree and result back
accurately if there were circular symbolic links.

So, you have the legacy code that uses java.io.File and would prefer taking benefit of the java.nio.file.
Path functionality with minimal impact on your code. The various legacy classes defined by java.util
package are:
 Dictionary
 Hashtable
 Stack
 Vector
 Properties

The Java Native Interface is developed for using Java in order to encapsulate native legacy code on
small embedded platforms. We must know why existing technologies for encapsulating legacy code,
Java Native Interface (JNI), is not enough for an important range of small embedded platforms, and we
depict how the JNI provides previously missing functionality.

12.13.1 The Vector Class


The Vector class predates the collection framework, and it implements a dynamic array. Because of the
appearance of the collection framework, Vector has been rewritten to be compatible with it. Here’s the
inheritance diagram for Vector:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
| java.util.Vector

33
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

You will find the fields of the Vector class in Table 34, its constructors in Table 35, and its methods in
Table 36:

Table 34: Fields of the Vector class

Field Does this


protected int capacityIncrement This is the amount by which the capacity of the vector is increased when
its size exceeds its capacity.
protected int elementCount Total number of components in this Vector object.
protected Object[] elementData The array where the components of the vector are stored.

Table 35: Constructors of the Vector class

Constructor Does this


Vector() It constructs an empty vector.
Vector(Collection c) It constructs a vector containing the elements of the given collection.
Vector(int initialCapacity) It constructs an empty vector with the given initial capacity.
Vector(int initialCapacity, int It constructs an empty vector with the given initial capacity and capacity
capacityIncrement) increment.

Table 36: Methods of the Vector class

Method Does this


void add(int index, Object It inserts the given element.
element)
boolean add(Object o) It adds the given element to the end of this vector.
boolean addAll It adds all the elements in the given collection to the end of this vector in
(Collection c) the order that they are returned by the given collection’s iterator.

boolean addAll(int index, It inserts all the elements in the given collection into this vector at the
Collection c) given position.

void addElement(Object obj) It adds the given component to the end of this vector, increasing its size
by one.
int capacity() It gets the current capacity of this vector.
void clear() It removes all the elements from this vector.
Object clone() It gets a clone of this vector.
Object elementAt(int index) It gets the component at the given index.
Enumeration elements() It gets an enumeration of the components of this vector.
int indexOf(Object elem) It returns the index of the first occurrence of the given element. In this
vector, or -1 if this vector does not contain element.
int indexOf It searches for the first occurrence of the given argument, beginning the
(Object elem, int index) search at index.

void insertElementAt It inserts the given object as a component in this vector at the given index.
(Object obj, int index)

34
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


boolean isEmpty() It tests whether this vector has no components.
Object lastElement() It gets the last component of the vector.
int lastIndexOf It gets the index of the last occurrence of the specified element in this
(Object elem) vector or -1 if this vector does not contain the element.

Each vector has a capacity, which is the maximum size it can grow to. When you exceed that size, the
capacity is automatically increased. You can use the add() and addElement() methods to add elements
to a vector, the remove() and removeElement() methods to remove elements, and the contains() method
to do a search.

12.13.2 The Stack Class


The Stack class is built on the Vector class, and it implements a stack construct. Here’s the inheritance
diagram for the Stack class:
java.lang.Object
| java.util.AbstractCollection
| java.util.AbstractList
| java.util.Vector
| java.util.Stack
You will find the constructor for the Stack class in Table 37 and its methods in Table 38:

Table 37: The constructor of the Stack class

Constructor Does this


Stack() It creates an empty stack.

Table 38: Methods of the Stack class

Method Does this


boolean empty() It returns True if this stack is empty.
Object peek() It gets the object at the top of this stack without removing it.
Object pop() It removes the object at the top of this stack and returns that object.
Object push(Object item) It adds an item onto the top of this stack.
int search(Object o) It gets the position of an object on this stack.

You use the push() method to add an element to a stack and the pop() method to retrieve it; note that
elements come off a stack in the reverse order in which they were added to it. Consider Program 6 in
which we push and then pop elements on a stack:
Program 6: Pushing and then popping elements on a stack
import java.util.*;

class StackDemo
{
public static void main(String args[])
{

35
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Stack<Integer> stack1 = new Stack<Integer>();


try {
stack1.push(new Integer(0));
stack1.push(new Integer(1));
stack1.push(new Integer(2));
stack1.push(new Integer(3));
stack1.push(new Integer(4));
stack1.push(new Integer(5));
stack1.push(new Integer(6));

System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
System.out.println((Integer) stack1.pop());
}
catch (EmptyStackException e) { }
}
}
Here’s the output of this example:
D:\Java folder\java StackDemo
6
5
4
3
2
1
0

12.3.3 The Dictionary Class


The Dictionary class is a class used by classes, such as Hashtable, and it stores elements much like a
map does, although it was introduced before the collection framework appeared. Because it forms the
foundation of the Hashtable class, we will include Dictionary here for reference. Here’s the inheritance
diagram for the Dictionary:
java.lang.Object
| java.util.Dictionary
You will find the constructor for Dictionary in Table 39 and its methods in Table 40:

Table 39: The constructor of the Dictionary class

Constructor Does this


Dictionary() It creates a dictionary.

36
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Table 40: Methods of the Dictionary class

Method Does this


abstract Enumeration It gets an enumeration of the values in this dictionary.
elements()
abstract Object get It gets the value for this key.
(Object key)
abstract boolean isEmpty() It returns True if this dictionary has no keys.
abstract Enumeration keys() It gets an enumeration of the keys in this dictionary.
abstract Object put It maps the given key to the given value in this dictionary.
(Object key, Object value)
abstract Object remove It removes the key and its value from this dictionary.
(Object key)
abstract int size() It gets the number of entries in this dictionary.

12.3.4 The Hashtable Class


The Hashtable class implements the Map interface, and it was how you used to implement maps before
the collection framework come. Here’s the inheritance diagram for Hashtable:
java.lang.Object
| java.util.Dictionary
| java.util.Hashtable
You will find the constructors for the Hashtable class in Table 41 and its methods in Table 42:

Table 41: Constructors of the Hashtable class

Constructor Does this


Hashtable() It constructs a new, empty hashtable.
Hashtable (int initialCapacity) It constructs a new, empty hashtable with the given initial capacity.
Hashtable(int initialCapacity, float It constructs a new, empty hashtable with the given initial capacity and
loadFactor) the given load factor.
Hashtable(Map t) It constructs a new hashtable with the same mappings as the given map.

Table 42: Methods of the Hashtable class

Method Does this


void clear() It clears this hashtable so that it contains no keys.
Object clone() It creates a copy of this hashtable.
boolean contains It returns True if some key maps into the given value in this hashtable.
(Object value)
boolean containsKey It returns True if the given object is a key in this hashtable.
(Object key)

37
JGI JAIN
DEEMED-TO-BE UNIVERSIT Y
Java Programming

Method Does this


boolean containsValue It returns True if this hashtable maps one or more keys to this value.
(Object value)
Enumeration elements() It gets an enumeration of the values in this hashtable.
Set entrySet() It gets a set view of the entries contained in this hashtable.
boolean equals(Object o) It compares the given object with this map for equality.
Object get(Object key) It gets the value to which the given key is mapped in this hashtable.
int hashCode() It gets the hashcode value for this map, as per the definition in the Map
interface.
boolean isEmpty() It tests whether this hashtable maps no keys to values.
Enumeration keys() It gets an enumeration of the keys in this hashtable.

You store and retrieve key/value pairs in a hashtable using the put() and get() methods. You can get an
Enumeration object for the keys in a hashtable using the keys() method, and you can use that object to
loop over the elements of the hash.

12.3.5 The Properties Class


The Properties class is derived from the Hashtable class (see the previous solution) and uses string
keys and values. This class maintains the properties of various other classes, and an object of the
Properties class is returned by those classes’s getProperty() method. Here’s the inheritance diagram for
the Properties class:
java.lang.Object
| java.util.Dictionary
| java.util.Hashtable
| java.util.Properties
You will find the single field of the Properties class in Table 43, its constructors in Table 44, and its
methods in Table 45:

Table 43: The field of the Properties class

Field Does this


protected Properties A property list that contains default values for keys
defaults

Table 44: Constructors of the Properties class

Constructor Does this


Properties() It constructs a property list.
Properties(Properties defaults) It constructs a property list with the given defaults.

Table 45: Methods of the Properties class

Method Does this


String getProperty It searches for the property with the given key.
(String key)

38
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

Method Does this


String getProperty It searches for the property with the given key and returns the default
(String key, String defaultValue) value if the key is not found.

void list(PrintStream out) It prints this property list to the given output stream.
void list(PrintWriter out) It prints this property list to the given writer stream.
void load It reads a property list from the input stream.
(InputStream inStream)
Enumeration propertyNames() It gets an enumeration of all the keys in this property list.
void save(OutputStream out, String It is deprecated and it uses the store method instead.
header)
Object setProperty It calls the hashtable method put.
(String key, String value)
void store It writes this property list in this Properties table to the output stream in
(OutputStream out, String a format acceptable for use with the load method.

header)
Set <String> It returns a set of keys in this property list where the key and its
stringPropertyNames() corresponding value are strings, including distinct keys in the default
property list if a key of the same name has not already been found from
the main properties list.

You can put property values into a Properties object with the setProperty() method, and you can get
property values with the getProperty() method. Consider program 7 in which we create a Properties
object, add property values to it, and then retrieve a property value. Note, in particular, that you can
supply a default value to getProperty() that it will return if there’s no property value matching the
property you have requested:
Program 7: Creating a Properties object, adding property values to it, and then retrieving a property
value
import java.util.*;

class PropertiesDemo
{
public static void main(String args[])
{
Properties properties1 = new Properties();
Set states; String outString;
properties1.setProperty("Property 0", "Value 0");
properties1.setProperty("Property 1", "Value 1");
properties1.setProperty("Property 2", "Value 2");
properties1.setProperty("Property 3", "Value 3");
properties1.setProperty("Property 4", "Value 4");
properties1.setProperty("Property 5", "Value 5");
properties1.setProperty("Property 6", "Value 6");
outString = properties1.getProperty("Property 3", "Missing");

39
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming

System.out.println(outString);
outString = properties1.getProperty("Property 7", "Missing");
System.out.println(outString);
}
}
Output of program 7:
D:\Java folder\java PropertiesDemo
Value 3
Missing

Conclusion 12.14 CONCLUSION

 A collection is an object that organises multiple data items into a single group.
 The collection framework provides a standardised way to handle a group of objects.
 Collections store, retrieve and manipulate the collection of data items. Here, a collection of data
implies the formation of a natural group of data items, such as collection of cards, collection of
letters, collection of books, collections of contacts in your mobile phone.
 The collections framework defines several interfaces and classes provided under the java.util
package.
 Prior to Java 2, ad hoc classes, such as Dictionary, Vector Stack and Properties, were used to store
and manipulate groups of objects.
 The Collection interface revolves around the objects to provide maximum generality. For example,
all general-purpose collection executions have a constructor that takes Collection parameter.
 The List interface is the foundation of classes, such as LinkedList and ArrayList. It is basically an
extension of the Collection interface that stores the behaviour of a collection.
 Sometimes you need to traverse the elements of a collection for some specific purpose, for instance
to display each element. To implement this, you need an iterator either using the Iterator interface
or using the ListIterator interface.
 RandomAccess is an empty interface or called a marker interface.
 A map is an object that stores associations between keys and values in pairs. It stores data in key/
value pairs, much like an array, where the indexes are, themselves, objects.

12.15 GLOSSARY

 Collection: Refers to an object that organises multiple data items into a single group.
 Collection framework: Provides a standardised way to handle a group of objects. Collections store,
retrieve and manipulate the collection of data items.
 List interface: Refers to the foundation of classes, such as LinkedList and ArrayList.
 Queue: Refers to a collection of elements to hold them before processing starts.
 Set: Refers to a group of unique elements, and the HashSet class supports sets that use a hash
internally for storage.

40
UNIT 12: The Collections Framework JGI JAIN
DEEMED-TO-BE UNIVERSIT Y

12.16 SELF-ASSESSMENT QUESTIONS

A. Essay Type Questions


1. Explain the concept of the collections framework.
2. Discuss the significance of Collection interfaces.
3. Describe various types of collection classes.
4. Elucidate the concept of Maps in Java.
5. Explain the significance of generic collections.

12.17 ANSWERS TO SELF-ASSESSMENT QUESTIONS

A. Hints for Essay Type Questions


1. The collection framework provides a standardised way to handle a group of objects. Collections
store, retrieve and manipulate the collection of data items. Refer to Section Collections Framework.
2. The Collection interface revolves around the objects to provide maximum generality. For example,
all general-purpose collection executions have a constructor that takes Collection parameter. Refer
to Section The Collection Interfaces.
3. The collection framework provides various abstract and non-abstract classes that implements
collection interfaces. Refer to Section The Collection Classes.
4. A map is an object that stores associations between keys and values in pairs. It stores data in key/
value pairs, much like an array, where the indexes are, themselves, objects. Refer to Section Working
With Maps.
5. One important feature of Java programming is that it is type-safe. If you assign a value to a variable
of a different data type without typecasting, the compiler generates an error. Refer to Section Why
generic collections.

@ 12.18 POST-UNIT READING MATERIAL

 https://www.logicbig.com/tutorials/core-java-tutorial/java-11-changes/collection-changes.html

12.19 TOPICS FOR DISCUSSION FORUMS

 Search and enlist the collections framework enhancements in Java SE 8.

Lab Exercises
Lab Exercise: Write a Java program to store a list of strings by implementing ArrayList and using
Iterator, traverse the elements of a list and display it on the console.
Solution:
import java.util.*;
class ArrayListDemo
{
public static void main(String args[]) 41
{
ArrayList<String> al=new ArrayList<String>();
al.add("Deepak");
JGI JAINDEEMED-TO-BE UNIVERSIT Y
Java Programming

al.add("Chirag");
al.add("Divya");
al.add("Alice");
al.add("John");
al.add("Goransh");
al.add("Meenal");
Iterator<String> it = al.iterator();
while (it.hasNext())
{
System.out.print(it.next() + "\n");
}
}
}

Explanation
In this program, we have created object of the ArrayList class with the String parameter to make a
String type array list. Next, we have added items in the array list by using the add( ) method of the
ArrayList class. We have used the Iterator interface to fetch all the items from the array list with the help
of iterator() method of the ArrayList class. Finally, all the items are printed with the help of hasNext( )
method and while loop.
Output:
Deepak
Chirag
Divya
Alice
John
Goransh
Meenal

42

You might also like