0% found this document useful (0 votes)
20 views79 pages

The Collections Framework Part 1

Uploaded by

charanmekala17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views79 pages

The Collections Framework Part 1

Uploaded by

charanmekala17
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Unit –IV

The Collections
Framework
Unit 4 The Collections Framework

(java.util)
Collections Overview  Arrays
 Collection Interfaces  The Legacy Classes and
 The Collection classes
Interfaces-
 Array List,
 Dictionary,
 Linked List,
 Hashtable ,
 Hash Set,
 Properties,
 Tree Set,
 Stack,
 Priority Queue,
 Vector
 Array Deque.
 More Utility classes,
 Accessing a Collection via an Iterator,  String Tokenizer,
 Using an Iterator,  Bit Set,
 The For-Each alternative  Date,
 Maps  Calendar,
 Map Interfaces  Random,
 Formatter,
 Classes,
 Scanner.
 Comparators, 2

 Collection algorithms,
Collections overview
 Collections framework in Java is one of the most valuable and
interesting topic of Java language. How important it is? Without
using the collection concept, you cannot develop any project.
 Initially, collection framework is simply called Java.util package or
Collection API. Later on, The Sun Microsystem has introduced the
collection framework in Java 1.2. It was developed and designed by
“Joshua Bloch”.
 Later on, after Java 1.2, it is known as the collections framework.
 From Java 1.5 onwards, The Sun Microsystem added some more new
concepts called Generics. Due to adding Generics concepts, a lot of changes
happened in the collections classes. That’s why Java 1.5 onwards, people
started calling it Collections and Generics. 3
Collection
 A collection is a group of objects. In Java, these objects are called
elements of the collection.
 Real-time Examples:
• In the kiddy bank, you had collected a lot of coins.
This kiddy bank is called collection and the coins are
nothing but objects.

• Put all the important books in the school bag before


going to school. Here Schoolbag is a collection and
books are objects.

• A classroom is a collection of students. So, the


classroom is nothing but a collection and students
are objects.

• The entire world is the collection of humans,


animals, and different things. The world is a 4
collection and humans, animals and different things
are different objects.
Collection
 Technically, A collection is an object which stores a group of
other objects as a single unit or single entity.
 Therefore, it is also known as container object in java. Container
object mean it contains other objects.
 JVM stores the reference of other objects into a collection object.
 It never stores copies of other objects because other objects are
already available in the memory and storing another copy of objects into a
collection object would be a wasting of memory.

5
• A collection object has a class that is known as collection class or container
class. All collection classes are present in java.util package. Here, util stands for
utility. A group of collection classes is called collection framework in java.
6
Types of Objects Stored in Collection
Object
 There are two types of objects that can be stored in a
collection or container object. They are as follows:
1. Homogeneous objects
2. Heterogeneous objects
1. Duplicate objects
2. Unique objects

7
Types of Objects Stored in Collection
Object
 There are two types of objects that can be stored in a
collection or container object. They are as follows:
1. Homogeneous objects
 Homo means same. Homogeneous objects are a group of multiple objects
that belong to the same class.
 For example:
 Suppose we have created three objects Student s1, Student s2, and Student s3 of
the same class ‘Student’. Since these three objects belong to the same class that’s
why they are called homogeneous objects.
1. Heterogeneous objects
1. Duplicate objects
2. Unique objects
8
Types of Objects Stored in Collection
Object
 There are two types of objects that can be stored in a
collection or container object. They are as follows:
1. Homogeneous objects
2. Heterogeneous objects
 Hetero means different. Heterogeneous objects are a group of different
objects that belong to different classes.
 For example:
 Suppose we have created two different objects of different classes such as one
object Student s1 and another one object Employee e1. Here, student and
employee objects together are called a collection of heterogeneous objects.
1. Duplicate objects
2. Unique objects
9
Types of Objects Stored in Collection
Object
 There are two types of objects that can be stored in a collection or
container object. They are as follows:
1. Homogeneous objects
2. Heterogeneous objects
1. Duplicate objects
 The multiple objects of a class that contains the same data are called duplicate objects.
 For example:
 Suppose we create two person objects Person p1 and Person p2. Both of these objects have
the same data.
Person p1=new Person(“abc”);
Person p2=new Person(“abc”);
 Since the above two objects have the same data “abc” therefore, these are called duplicate
objects.
2. Unique objects
10
Types of Objects Stored in Collection
Object
 There are two types of objects that can be stored in a
collection or container object. They are as follows:
1. Homogeneous objects
2. Heterogeneous objects
1. Duplicate objects
2. Unique objects
 The multiple objects of a class that contains different data are called unique
objects.
 For example
Person p1=new Person(“abcd“);
Person p2=new Person(“abcde“);
 Unique or duplicate object depends on its internal data.

11
Need of Collection
 Before going to understand the need for collection in java,
first, we understand different ways to store values in Java
application by JVM.
 There is total of four ways to store values in Java application
by JVM.
1. Using a variable approach
2. Using a class object approach
3. Using an array object approach
4. Using a collection object

12
Using a variable approach
 Suppose you want to store one value in the memory then you will create one variable and assign
a value like this
 int x=10;
 The purpose of variable x is to store one int value 10. If we want to store two int values, we will create two variables
like
 int x=10;
 int y=20;
 Similarly, for three values, the third variable will be required and so on.
 There is no problem to store until the third or fourth value. But if we want to store 5000 values
then declaring 5000 variables in a program is the worst kind of programming practice and it
will not be in the readable format.
 Thus, the limitations of using the variable approach are as follows:
 ➲ The limitation of a variable is that it can store only one value at a time.
 ➲ Readability and reusability of the code will be down.
 ➲ JVM will take more time for the execution.
 Hence, the problem facing with this approach can be overcome by using the second approac13h
“Class object”.
Using a class object approach
 Using a class object, we can store multiple “fixed” number of values of different
types.
 For example,
 suppose we have created a class named Employee and declare two variables inside the
class.
class Employee {
int eNo;
String eName;
}
 If we create an object of Employee class like
Employee e1=new Employee();
So can you think how many values can store in this employee object?
 The answer is only two but if you will want to store the third value, it will not possible.
Therefore, this approach is only suitable to store a fixed number of different values. To
overcome this problem, we should use third technique “Array object”. 14
Using an array object approach
 We can store a group of objects
into an array.
 Let’s take an example to
understand it.
 Suppose we want to store 5000
objects of Student class into an
array.
 For this purpose, we need to
create an array object of Student
type like this:
 Student[ ] st=new Student[5000];
This array can store 5000 Student 15
objects.
 The biggest advantage of an array is that we can store a
huge number of values by using a single variable st and
retrieve them easily.
 Array mechanism helps to improve the readability of the code
in java programming but there are several types of problems
and limitations with the array.

16
limitations with the array
1. We can easily store multiple “fixed” numbers of values of homogeneous data type
i.e. Array can store only similar types of data.
 Suppose if we create Employee type array object
Employee[ ] emp=new Employee[5000]; // it will hold only employee type objects.
For example:
emp[0]=new Employee(); // valid.
emp[1]=new Customer(); // invalid because here, we are providing the customertype
object.
We can resolve this problem by using an object array.
Object[ ] ob=new Object[5000];
ob[0]=new Employee(); // valid.
ob[1]=new Customer(); // valid.
2. An array is static in nature. It is fixed in length and size.
 We cannot change (increase/decrease) the size of the array based on our requirements once
they created. Hence, to use an array, it is compulsory that we should know the size of anarray
to store a group of objects in advance which may not be possible always.
17
limitations with the array
3. We can add elements at the end of an array easily. But, adding and deleting
elements or objects in the middle of array is difficult.
4. We cannot insert elements in some sorting order using array concept because
array does not support any method.
 We will have to write the sorting code for this but in the case of collection, ready-made
method support is available for sorting using Tree set.
5. We cannot search a particular element using an array,
 Whether the particular element is present or not in the array index.
 For this, we will have to write the searching code using array but in the case of collection, one
readymade method called contains() method is available.
 Due to all these above limitations of array, programmers need a better
mechanism to store a group of objects. So, the alternative option is a collection
object or container object in java.
18
Using a collection object
 By using a collection object, we can store the same or
different data without any size limitation.
 Thus, technically, we can define the collection as:
A collection in java is a container object that is used for
storing multiple homogeneous and heterogeneous, duplicate
and unique elements without any size limitation.

19
Framework
 A framework in java is a set of several classes and
interfaces which provide a ready-made architecture

20
Collections Framework
 A Java collections Framework is a sophisticated hierarchy of
several predefined interfaces and implementation classes that
can be used to handle a group of objects as a single entity.
 It is present in java.util package. It allows us to store,
retrieve, and update a group of objects.
 The java collections framework provides an API to work with
data structure such as lists, trees, sets, and maps.

21
 The list of interfaces defined in java.util package is
shown inthe below table:

22
23
Difference between Arrays & Collections
in Java
 The difference between arrays and collections are as follows:
1. Arrays are fixed in size but collections are growable in nature. We can
increase or decrease size.
2. Arrays are not recommended to use with respect to memory whereas
collections are recommended to use with respect to memory.
3. Arrays are recommended to use with respect to performance but collections
are not recommended to use with respect to performance.
4. Arrays can store only homogeneous data elements (similar type of data) but
collections can hold both homogeneous and heterogeneous elements.
5. Arrays do not support any method but collections support various kinds of
methods.
6. Arrays can have both hold primitives and object types but collections can
hold only objects but not primitive. 24
Advantages of Collection Framework
 The advantages of the collections framework in java
are asfollows:
1. The collections framework reduces the development time and
the burden of designers, programmers, and users.
2. Your code is easier to maintain because it provides useful data
structure and interfaces which reduce programming efforts.
3. The size of the container is growable in nature.
4. It implements high-performance of useful data structures and
algorithms that increase the performance.
5. It enables software reuse.
25
Limitations of Collection Framework
 There are two limitations to java collection framework.
They are as follows:
1. Care must be taken to use the appropriate cast operation.
2. Compile type checking is not possible.

26
Collection Hierarchy
 The hierarchy of the entire collection framework consists of
four core interface
 such as Collection, List, Set, Map, and two specialized interfaces
named SortedSet and SortedMap for sorting.
 All the interfaces and classes for the collection framework are
located in java.util package.

27
• e➝ extends, I➝ implements.
• Extends: Extends is a keyword
that is used for developing
inheritance between two
classes and two interfaces.
• Implements: Implements is a
keyword used for developing
inheritance between class and
interface.

28
Collection Interface

29
Collection Interface
 ➲ The basic interface of the collections framework is the
Collection interface which is the root interface of all collections in
the API (Application programming interface) and placed at the top
of the collection hierarchy.
 ➲ Collection interface extends the Iterable interface.
 The iterable interface has only one method called iterator().
 The function of the iterator method is to return the iterator object.
 Using this iterator object, we can iterate over the elements of the
collection.
 ➲ List, Queue, and Set have three component which extends the
collection interface. A map is not inherited by the collection
interface. 30
Methods of Collection interface
No. Method Description
1 • public boolean add(E e) • It is used to insert an element in this
collection.
2 • public boolean addAll(Collection<? extends E> c) • It is used to insert the specified
collection elements in the invoking
collection.
3 • public boolean remove(Object element) • It is used to delete an element from the
collection.
4 • public boolean removeAll(Collection<?> c) • It is used to delete all the elements of
the specified collection from the
invoking collection.
5 • default boolean removeIf(Predicate<? super E> filter) • It is used to delete all the elements of
the collection that satisfy the specified
predicate.
6 • public boolean retainAll(Collection<?> c) • It is used to delete all the elements of
invoking collection except the specified
collection.
7 • public int size() • It returns the total number of elements 31
in the collection.
Methods of Collection interface
No. Method Description
8 • public void clear() • It removes the total number of elements
from the collection.
9 • public boolean contains(Object element) • It is used to search an element.
10 • public boolean containsAll(Collection<?> c) • It is used to search the specified
collection in the collection.
11 • public Iterator iterator() • It returns an iterator.
12 • public Object[] toArray() • It converts collection into array.
13 • public <T> T[] toArray(T[] a) • It converts collection into array. Here,
the runtime type of the returned array is
that of the specified array.
14 • public boolean isEmpty() • It checks if collection is empty.
15 • default Stream<E> parallelStream() • It returns a possibly parallel Stream with
the collection as its source.
16 • default Stream<E> stream() • It returns a sequential Stream with the
collection as its source.

32
Methods of Collection interface
No. Method Description
17 • default Spliterator<E> spliterator() • It generates a Spliterator over the
specified elements in the collec tion.
18 • public boolean equals(Object element) • It matches two collections.
19 • public int hashCode() • It returns the hash code number of the
collection.

33
Collection Interface
1. The Collection Interface
1. The List Interface
2. The Set Interface
 The SortedSet Interface
 The NavigableSet Interface
3. The Queue Interface
The Deque Interface
2. Map
 SortedMap
 NavigableMap
34
List Interface
 A list is the subinterface of a collection which is available in java.util
package.
 It inhibits a list type data structure in which we can store the ordered
collection of objects. It can have duplicate values.
 List interface is implemented by the classes ArrayList, LinkedList, Vector, and
Stack.
 To instantiate the List interface, we must use :

36
Properties of List Interface
1. The list allows storing duplicate elements in Java.
2. It maintains insertion order. i.e. List can preserve the insertion
order by using the index.
3. It allows for storing many null keys.
4. The list uses a Resizable array for their implementation.
 Resizable means we can increase or decrease the size of the array.
5. Except for LinkedList, ArrayList, and Vector is indexed based
structure.

37
Properties of List Interface
6. It provides a special Iterator called a ListIterator that allow
accessing the elements in the forward direction using
hasNext() and next() methods.
 In reverse direction, it access elements using hasPrevious() and
previous() methods. We can add, remove elements of the collection
and can also replace the existing elements with the new element
using ListIterator.

38
Methods of List Interface
1. boolean add(int index,Object o);
2. boolean addAll(int index,Collectio c);
3. Object get(int index);
4. Object remove(int index);
5. Object set(int index,Object new);
6. Int indexOf(Object o);
7. Returns index of first occurrence of "o".
8. Int lastIndexOf(Object o);
9. ListIterator listIterator();

39
Set Interface
 A set in Java is a collection of elements or objects that are not
stored in a particular order.
 It is used to store the collection of elements without duplicate.
 i.e. Set does not allow the duplicate elements. It contains the unique
elements.
 It will not add an element to the set if the set already contains
that element.
 It is an unordered collection.
 That means the order is not maintained while storing elements. While
retrieving we may not get the same order as that we put elements.
40
Set Interface
 Java Set uses the Map based structure for their
implementation.
 Set can be iterated by using Iterator but cannot be iterated by
using ListIterator.
 Most of the set implementations allow adding only one
null element.
 Treeset does not allow to add the null element.
 Set is not indexed based structure in Java.
 Therefore, we cannot access elements by their index position.
 It does not provide any get method like a list.
41
Set Hierarchy

43
44
Methods
SN Method Description
• It is used to add the specified el ement
1 • boolean add(Object o)
in this set.
• This method adds all the elements in
2 • boolean addAll(Collection c)
the given collection.
• It is used to get the number of
3 • int size()
elements in the set.
• This method checks that the set is
4 • boolean isEmpty()
empty or not.
• It is used to remove all the elements
5 • void clear()
from the set.
• This method returns true if this set
6 • boolean contains(Object o)
contains the given element.
• This method returns true if this set
7 • boolean containsAll(Collection c) contains all the elements of the given
collection. 44
Methods
SN Method Description
• It is used to remove the specifi ed
8 • boolean remove(Object o)
element from this set.
• It removes all the elements in the given
9 • boolean removeAll(Collection c)
collection from the set.
• It returns an Iterator over the elements
10 • Iterator iterate()
in this set.
• It is used to compare the given element
11 • boolean equals(Object o)
for equility in this set.
• It is used to get the hashCode value for
12 • int hashCode()
this set.

46
Set is a Generic interface that has this
declaration
 Interface Set<E>
•  E specifies the type of Object that has set will hold
 We can create a generic Set object by using the
implementation of the HashSet, LInkedHashSet, TreeSet etc
like this:
 Syntax:
• Set<T> set=new HashSet<T>(); where T is the type of generic.
• Set<T> set=new LinkedHashSet<T>();
• Set<T> set=new TreeSet<T>();
• For example:
• Set<Integer> set=new HashSet<Integer>();
• Set<String> set1=new LinkedHashSet<String>();
47
When to use Set
 If you want to represent a group of individual elements as a
single entity where duplicates are not allowed and insertion
order are not preserved then we should go for the Set.
 If your requirement is to get the unique elements, the Set is
the best choice for this.
 If you want to remove duplicate elements without maintaining
an insertion order from the non-set collection, you should go
for the set.

48
49
50
51
SortedSet Interface
 SortedSet is the alternate of Set interface that provides a total
ordering on its elements.
 The elements of the SortedSet are arranged in the increasing
(ascending) order.
 The SortedSet provides the additional methods that inhibit the
natural ordering of the elements.
 The SortedSet can be instantiated as:

52
Methods of SortedSet
 The SortedSet interface includes all the methods of the Set interface. It's
because Set is a super interface of SortedSet.
 Besides methods included in the Set interface, the SortedSet interface also
includes these methods:
 comparator() - returns a comparator that can be used to order elements in the
set
 first() - returns the first element of the set

 last() - returns the last element of the set

 headSet(element) - returns all the elements of the set before the specified
element
 tailSet(element) - returns all the elements of the set after the specified element
including the specified element
 subSet(element1, element2) - returns all the elements between the element1 52

and element2 including element1


54
55
NavigableSet Interface
 The NavigableSet interface of the java
Collections framework provides the
features to navigate among the set
elements.
 It is considered as a type of SortedSet.

 Class that implements NavigableSet


 In order to use the functionalities of
the NavigableSet interface,
 we need to use the TreeSet class that implements
NavigableSet.
56
How to use NavigableSet?
 In Java, we must import the java.util.NavigableSet
package to use NavigableSet.
 // SortedSet implementation by TreeSet class

NavigableSet<String> numbers = new TreeSet<>();


 Here, we have created a navigable set named numbers of
the TreeSet class.

57
Methods of NavigableSet
 The NavigableSet is considered as a type of SortedSet.
 It is because NavigableSet extends the SortedSet interface.
 Hence, all SortedSet methods are also available in
NavigableSet.
 However, some of the methods of SortedSet ()
 headSet(),
 tailSet() and
 subSet()) are defined differently in NavigableSet.

58
headSet(element, booleanValue)
 The headSet() method returns all the elements of a navigable
set before the specified element (which is passed as an
argument).
 The booleanValue parameter is optional. Its default value is
false.
 If true is passed as a booleanValue,
 the method returns all the elements before the specified
element including the specified element.

59
tailSet(element, booleanValue)
 The tailSet() method returns all the elements of a navigable
set after the specified element (which is passed as an
argument) including the specified element.
 The booleanValue parameter is optional. Its default value
is itrue.
 If false is passed as a booleanValue, the method returns all the
elements after the specified element without including the specified
element.
subSet(e1, bv1, e2, bv2)
 The subSet() method returns all the elements between e1
and e2 including e1.
 The bv1 and bv2 are optional parameters. The default value of bv1 is
true, and the default value of bv2 is false.
 If false is passed as bv1, the method returns all the elements
between e1 and e2 without including e1.
 If true is passed as bv2, the method returns all the elements
between e1 and e2, including e1.

61
Methods for Navigation
 The NavigableSet provides various methods that can be used to navigate over its
elements.
 descendingSet() - reverses the order of elements in a set

 descendingIterator() - returns an iterator that can be used to iterate over a set in


reverse order
 ceiling() - returns the lowest element among those elements that are greaterthan
or equal to the specified element
 floor() - returns the greatest element among those elements that are less than or
equal to the specified element
 higher() - returns the lowest element among those elements that are greater than
the specified element
 lower() - returns the greatest element among those elements that are less than
the specified element
 pollFirst() - returns and removes the first element from the set
62
 pollLast() - returns and removes the last element from the set
63
The Queue interface
 A queue is an ordered of the homogeneous group of
elements in which new elements are added at one end(rear)
and elements are removed from the other end(front).
 Just like a queue in a supermarket or any shop.
 This interface represents a special type of list whose
elements are removed only from the head.

64
Hierarchy of Queue Interface

65
Classes that Implement Queue
 Since the Queue is an interface, we cannot provide the direct
implementation of it.
 In order to use the functionalities of Queue, we need to use
classes that implement it:
 ArrayDeque
 LinkedList
 PriorityQueue
Interfaces that extend Queue
 The Queue interface is also extended by various subinterfaces:
 Deque
 BlockingQueue
 BlockingDeque

67
Working of Queue Data Structure
 In queues, elements are stored and accessed in First In, First
Out manner.
 That is, elements are added from the behind and removed
from the front.

68
How to use Queue?
 In Java, we must import java.util.Queue package in order to
use Queue.

 Here, we have created objects animal1, animal2 and animal3 of


classes LinkedList, ArrayDeque and PriorityQueue respectively.
 These objects can use the functionalities of the Queue interface. 68
Methods of Queue
 The Queue interface includes all the methods of the Collection interface.
 It is because Collection is the super interface of Queue.
 Some of the commonly used methods of the Queue interface are:
 add() - Inserts the specified element into the queue. If the task is successful, add()
returns true, if not it throws an exception.
 offer() - Inserts the specified element into the queue. If the task is successful,
offer() returns true, if not it returns false.
 element() - Returns the head of the queue. Throws an exception if the queue is
empty.
 peek() - Returns the head of the queue. Returns null if the queue is empty.

 remove() - Returns and removes the head of the queue. Throws an exception if
the queue is empty.
 poll() - Returns and removes the head of the queue. Returns null if the queue is
69
empty.
71
72
The Deque Interface
 The Deque interface of the Java collections framework
provides the functionality of a double-ended queue.
 It extends the Queue interface.

 Working of Deque
 In a regular queue, elements are added from the rear and
removed from the front. However, in a deque, we can insert and
remove elements from both front and rear.

73
Classes that implement Deque
 In order to use the functionalities of the Deque interface, we
need to use classes that implement it:
 ArrayDeque
 LinkedList

74
How to use Deque?
 In Java, we must import the java.util.Deque package to
useDeque.

 Here, we have created objects animal1 and animal2 of classes


ArrayDeque and LinkedList, respectively.
 These objects can use the functionalities of the Deque interface.
74
Methods of Deque
 Since Deque extends the Queue interface, it inherits all
the methods of the Queue interface.
 Besides methods available in the Queue interface, the Deque
interface also includes the following methods:
 addFirst() - Adds the specified element at the beginning of the deque.
Throws an exception if the deque is full.
 addLast() - Adds the specified element at the end of the deque. Throws
an exception if the deque is full.
 offerFirst() - Adds the specified element at the beginning of the deque.
Returns false if the deque is full.
 offerLast() - Adds the specified element at the end of the deque. Returns
false if the deque is full. 75
Methods of Deque
 getFirst() - Returns the first element of the deque. Throws an exception if the
deque is empty.
 getLast() - Returns the last element of the deque. Throws an exception if the
deque is empty.
 peekFirst() - Returns the first element of the deque. Returns null if the deque is
empty.
 peekLast() - Returns the last element of the deque. Returns null if the deque is
empty.
 removeFirst() - Returns and removes the first element of the deque. Throws an
exception if the deque is empty.
 removeLast() - Returns and removes the last element of the deque. Throws an
exception if the deque is empty.
 pollFirst() - Returns and removes the first element of the deque. Returns null if
the deque is empty.
 pollLast() - Returns and removes the last element of the deque. Returns null if
the deque is empty. 76
Deque as Stack Data Structure
 The Stack class of the Java Collections framework provides
the implementation of the stack.
 However, it is recommended to use Deque as a stack instead of the
Stack class. It is because methods of Stack are synchronized.
 Here are the methods the Deque interface provides to
implement stack:
 push() - adds an element at the beginning of deque
 pop() - removes an element from the beginning of deque
 peek() - returns an element from the beginning of deque

78
79

You might also like