4 Unit4 Part1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Object Oriented Programming with

Java(BCS-403)
Unit-4
Prepared By Sandhya Avasthi
[email protected]
Assistant Professor
Department of Computer Science & Engineering
Table of Content
• Collection in Java, Collection Framework in Java
• Hierarchy of Collection Framework
• Iterator Interface
• Collection Interface
• List Interface
• ArrayList
• LinkedList
• Vector
• Stack
• Queue Interface
• Set Interface, Hash set, LinkedHashSet, TreeSet
What is Collection in Java?
• A Collection represents a single unit of objects, i.e., a group.
• In Java, a Collection is a root interface in the Java Collections Framework
(JCF).
• It represents a group of objects (known as elements) in a single unit
including Interfaces and its implementations, i.e., classes and Algorithm
• It is part of the java.util package and serves as the foundation for
various data structures and algorithms that operate on collections of
objects.
Type of Collections
Four main types of collections are:-
1. Queues allow the programmer to insert items in a certain order and
retrieve those items in the same order. An example is a waiting list.
The base interfaces for queues are called Queue.
2. Dictionaries/Maps store references to objects with a lookup key to
access the object's values. One example of a key is an identification
card. The base interface for dictionaries/maps is called Map.
3. Lists are finite collections where it can store the same value multiple
times
4. Sets are unordered collections that can be iterated and contain each
element at most once. The base interface for sets is called set.
Hierarchy of
Collection
Framework
• The java.util package
contains all
the classes and interfaces fo
r the Collection framework.
Hierarchy of Collection Framework
• it illustrates the relationships between different collection types and
their implementations.
• At the top is Iterable interface, which provides a way to iterate over
elements in a collection.
• It is the root interface for all collection types.
• Moving down, Collection interface is a child of Iterable and
represents a group of objects. It defines the common methods and
behaviors for all collection types.
Hierarchy of Collection Framework
There are three main interfaces in collection interface:
• List: An ordered collection that allows duplicate elements. Its
implementations are ArrayList, LinkedList, Vector, and Stack.
• Queue: A collection designed for holding elements prior to
processing. Its implementations are PriorityQueue, Deque, and
ArrayDeque.
• Set: An unordered collection that does not allow duplicate elements.
Its implementations are HashSet, LinkedHashSet, SortedSet, and
TreeSet.
Why collection framework?
• The Java collections framework provides various data structures and algorithms that
can be used directly.
• You do not have to write code to implement these data structures and algorithms
manually.
• Your code will be much more efficient as the collections framework is highly
optimized.
• the collections framework allows us to use a specific data structure for a particular
type of data.
• If we want our data to be unique, then we can use the set.
• To store data in key/value pairs, we can use the Map
• To have resizable array ,use ArrayList
Iterable Interface
• is the root interface for all the collection classes.
• The Collection interface extends the Iterable interface and therefore all
the subclasses of Collection interface also implement the Iterable
interface.
• It contains only one abstract method.
Collection Interface in Java
• The interface which is implemented by all the classes in the collection
framework. It declares the methods that every collection will have
• one of the root interfaces of the Collection Hierarchy
• It is not directly implemented by any class, but it is implemented
indirectly via its subtypes or sub-interfaces like List, Queue, and Set.
Key Features
• It is a part of java.util package .
• It implements the Iterable interface.
• sub-interfaces of Collection are List<E>, Set<E>, Queue<E>, and
others.
Collection interface and Various Methods(1)
SN Method Description/Use

1 public boolean add(E e) used to insert an element in this collection.

2 public boolean used to insert the specified collection


addAll(Collection<? extends E> c) elements in the invoking collection.

3 public boolean remove(Object to delete an element from the collection.


element)
4 public boolean to delete all elements of the specified
removeAll(Collection<?> c) collection from the invoking collection.

5 default boolean used to delete all elements of the collection


removeIf(Predicate<? super E> that satisfy the specified predicate.
filter)
Collection interface and Various Methods(2)
SN Method Description/Use

6 to delete all the elements of invoking


public boolean collection except the specified collection.
retainAll(Collection<?> c)
7 public int size() It returns the total number of elements in
the collection.
8 public void clear() It removes the total number of elements
from the collection.
9 public boolean contains(Object It is used to search an element.
element)
10 public boolean It is used to search the specified collection in
containsAll(Collection<?> c) the collection.
Collection interface and Various Methods(3)
SN Method Description/Use

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> It returns a possibly parallel Stream with the


parallelStream() collection as its source.
Collection interface and Various Methods(4)
SN Method Description/Use

16 default Stream<E> stream() It returns a sequential Stream with the


collection as its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified
elements in the collection.
18 public boolean equals(Object It matches two collections.
element)
19 public int hashCode() It returns the hash code number of the
collection.
Iterator Interface in Java
• It is part of the Java Collections Framework. It allows us to access and manipulate
elements in a collection, such as a Map, List, or Set.
• It is a universal iterator as it can be applied to any Collection object .
• It is one of the Java Cursors that are practiced to traverse the objects of the collection
framework.
Key Features
• It can traverse only in the forward direction .
• Both read and remove operations can be performed
• It was included in Java JDK 1.2 .
How to Declare?
• public interface Iterator<E>
Method in Iterator Interface
There four main methods available in Iterator interface:-
▪ hasNext()- it does not accept any parameter. It returns true if there are
more elements left in the iteration. If there are no more elements left, then
it will return false.
▪ next()- It returns next element in traversal. If the iteration or collection of
objects has no more elements left to iterate, then it throws the
NoSuchElementException.
▪ remove() -remove last element returned by the iterator traversing through
the underlying collection.
▪ forEachRemaining()- This method performs particular operation on all of
left components of the collection until all the components are consumed or
the action throws an exception.
List Interface in Java
• It is an interface and extends the Collection Interface
• It provides a way to store an ordered collection of objects, where
duplicate values can be stored
• Implementation classes of List interface are ArrayList, LinkedList, Stack,
and Vector.
• various methods in List interface that can be used to insert, delete, and
access elements from the list.
How to instantiate?
• List <data-type> list1= new ArrayList();
• List <data-type> list2 = new LinkedList();
• List <data-type> list3 = new Vector();
• List <data-type> list4 = new Stack();
List Interface in Java
There are three main classes in list interface
1. ArrayList
2. LinkedList
3. Vector
4. Stack
1. ArrayList Class
• It is used to implement resizable arrays.
• It’s part of the collections framework and implements
the List interface.
• Unlike standard arrays, ArrayList can automatically
adjust its capacity when elements are added or
removed, making it a dynamic array1.

Constructor to intitialize ArrayList


• ArrayList()- constructs an array with initial capacity of ten
• ArrayList(int n)- constructs a list of size n
• ArrayList( Collection E)- Constructs a list containing the elements of the specified
collection
Example 1 ArrayList
ArrayList in Java
import java.util.ArrayList;
In this example,
class Main {
an ArrayList named languages is
public static void main(String[] args) { created. The add() method is used
// Create an ArrayList to add elements to the ArrayList
ArrayList<String> languages = new ArrayList<>();

// Add elements to the ArrayList


languages.add("Java");
languages.add("Python");
languages.add("Swift");

System.out.println("ArrayList: " + languages);


}
}
Basic Operations on ArrayList
• Adding element to List/ Add element.
• Changing elements/ Set element.
• Removing elements/Delete element.
• Iterating elements.
• get elements.
• add elements in between two number.
2. LinkedList Class
• LinkedList implements the Collection interface.
• It uses a doubly linked list internally to store the elements.
• It can store the duplicate elements. It maintains the insertion order
and is not synchronized.
• manipulation is fast because no shifting is required.
Example Java Program
Basic operation on LinkedList
It provides various methods that allow us to perform different
operations in linked lists.
• Adding elements
• Accessing elements
• Changing/modifying elements
• Removing elements
Example1 Java program LinkedList
Example2 Java program LinkedList
3. Vector Class
• Vector uses a dynamic array to store data
elements
• It is similar to arraylist
• It is synchronized(only one thread at a time
can access the code) and contain many
methods that are not part of collections
• Like an array, it contains components that
can be accessed using an integer index.
• it gives a poor performance in adding,
searching, deleting, and updating its
elements.
Few Vector Methods
Example Program Vector
Stack Class
• The class is based on the basic principle of
last-in-first-out.
• performs basic push and pop operations
• class provides three more functions of
empty, search, and peek.
• This class extends Vector and treats the
class as a stack with the five mentioned
functions.
Methods in Stack Class
Method Description
empty() It returns true if nothing is on the top of the stack. Else, returns false.
peek() Returns the element on the top of the stack, but does not remove it.
Removes and returns the top element of the stack. An
pop() ‘EmptyStackException’
An exception is thrown if we call pop() when the invoking stack is empty.
push(Object
Pushes an element on top of the stack.
element)

It determines whether an object exists in the stack. If element is found, It


search(Object
returns the position of the element from the top of the stack. Else, it
element)
returns -1.
Queue Interface
• It represents a first-in, first-out (FIFO) queue of objects.
• It extends the Collection interface and adds the insertion, removal,
and inspection operations of a queue.
• It provides several methods for adding, removing, and inspecting
elements. Some of the key methods include:
boolean add(E e): Inserts specified element into queue if possible; otherwise, throws an
exception if the queue is full.
boolean offer(E e): Inserts specified element into queue if possible; otherwise, returns false.
E remove(): Retrieves and removes the head of the queue.
E poll(): Retrieves and removes the head of the queue, or returns null if the queue is empty.
E element(): Retrieves, but does not remove, the head of the queue.
E peek(): Retrieves, but does not remove, the head of the queue, or returns null if the queue
is empty.
Priority Queue
• A PriorityQueue is used when objects are supposed to be processed
based on the priority.
• It is known that a Queue follows the First-In-First-Out algorithm, but
sometimes the elements of the queue are needed to be processed
according to the priority.
• elements of the priority queue are ordered according to the natural
ordering
Limitations-
• PriorityQueue doesn’t permit null.
• You can’t create a PriorityQueue of Objects that are non-comparable
Deque Interface
• It is related to the double-ended queue that supports the addition or
removal of elements from either end of the data structure.
• It can either be used as a queue(first-in-first-out/FIFO) or as
a stack(last-in-first-out/LIFO).
• Deque is acronym for double-ended queue.
• Deque interface in Java is a sub-interface of the Queue interface
Example Program ArrayDeque
Example Java Program Priority Queue
Set Interface
➢It is a part of the java.util package and is used to store unique elements.
➢Unlike lists, which can store duplicate elements, sets do not allow
duplicates.
▪ Uniqueness: If you try to add a duplicate element to a set, it will be
ignored.
▪ Unordered Collection: The elements in a set are not stored in any
particular order. Sets do not maintain the insertion order of elements.
▪ Null Elements: A set can have at most one null element. If you try to add
a null element to a set that already contains a null element, the second
null element will be ignored.
Set Implementations
The Set interface has three concrete implementations in Java:
HashSet: commonly used implementation of the Set interface. It stores
elements in a hash table and does not maintain any order of elements.
LinkedHashSet: This implementation extends HashSet and maintains the
insertion order of elements.
TreeSet: Stores elements in a red-black tree structure, which means the
elements are sorted in ascending order according to their natural ordering
or by a Comparator provided at the creation time.
Common Methods-The Set interface provides several methods for working
with sets, such as add(), addAll(), remove(), removeAll(), contains(),
isEmpty(), size(), iterator(), and more.
HashSet
It is backed by a hash table data structure and provides constant-time performance for
basic operations like add(), remove(), and contains(), assuming that the hash function
disperses the elements properly among the buckets.
▪ Hash Table Implementation: HashSet internally uses a hash table to store its elements.
The hash table is implemented as an instance of HashMap.
▪ No Duplicates: it does not allow duplicate elements. When you try to add a duplicate
element, it is ignored.
▪ Null Elements: it allows at most one null element. If you try to add a second null
element, it will be ignored.
▪ No Order: Elements in a HashSet are not stored in any particular order. The order in
which elements are returned by the iterator may be different from order in which they
were inserted.
▪ Constant-Time Performance: The add(), remove(), and contains() operations have
constant-time performance on average, assuming a good hash function and a properly
sized hash table. However, in the worst case, when the hash table becomes too full
and needs to be resized, the performance can degrade to linear time.
Constructors of HashSet class
Different way you can initialize HashSet are:

• HashSET<E> hs=new HashSet<E>();


• HashSet<E> hs=new HashSet<E>(int intitialCapacity);
• HashSet<E> hs=new HashSet<E>(int intitialCapacity, float
loadFactor)
• HashSet<E> hs=new HashSet<E>(Collection c)
Example Program HashSet

Output ???
Java program
to show
union and
intersection
LinkedHash Set
Insertion Order- Unlike HashSet, LinkedHashSet maintains the insertion order
of elements. When iterating over the set, the elements are returned in the
order they were inserted.
Hash Table Implementation-Like HashSet, LinkedHashSet is also backed by a
hash table data structure (an instance of HashMap) for storing the elements.
This provides constant-time performance for basic operations like add(),
remove(), and contains().
Linked List Implementation- it maintains a doubly-linked list that keeps track
of insertion order of elements.
No Duplicates-it does not allow duplicate elements. When you try to add a
duplicate element, it is ignored.
Null Elements- it allows at most one null element. If you try to add a second
null element, it will be ignored.
LinkedHashSet Example
Sorted Set Interface
The SortedSet interface in Java extends the Set interface and provides a set that
maintains its elements in ascending order. It is part of the java.util package and is
primarily implemented by the TreeSet class.
Ordered Elements: The elements in a SortedSet are maintained in sorted order,
either by their natural ordering
No Duplicates: Like other Set implementations, a SortedSet does not allow duplicate
elements.
Null Elements: In general, a SortedSet does not allow null elements. However, some
implementations like TreeSet allow one null element.
Implementation: The primary implementation of the SortedSet interface is the
TreeSet class, which is backed by a self-balancing binary search tree (Red-Black
Tree).
Sorting and Searching: Because the elements are stored in sorted order, operations
like retrieving the smallest, largest, or n-th element, as well as searching for
elements, can be performed efficiently.
Iterators and Subsets: The SortedSet interface provides methods for retrieving
iterators that traverse the set in sorted order. It also allows you to retrieve subsets of
the set based on a range of elements.
TreeSet
▪ It is implementation of the SortedSet interface in Java. It is a self-balancing
binary search tree. Elements in a TreeSet are stored in ascending order
according to their natural ordering
▪ Ordering- stores its elements in sorted ascending order.
▪ No Duplicates: TreeSet does not allow duplicate elements.
▪ Null Handling: By default, TreeSet does not allow null elements.
▪ Self-Balancing: it is a self-balancing binary search tree (Red-Black tree). This
means that after every insertion or deletion operation, the tree is rebalanced to
maintain its height within reasonable limits, ensuring logarithmic time
complexity for operations like add(), remove(), and contains().
▪ Performance: The time complexity for basic operations like add(), remove(),
and contains() is O(log n) on average, where n is the number of elements in the
set. This makes TreeSet efficient for large datasets.
Methods in TreeSet
boolean addAll(Collection c)
Adds all of the elements in the specified collection to this set.
Object clone()
Returns a shallow copy of this TreeSet instance.
Comparator comparator()
Returns the comparator used to order this sorted set, or null if this tree set uses its elements
natural ordering.
SortedSet subSet(Object fromElement, Object toElement)
Returns a view of the portion of this set whose elements range from fromElement, inclusive,
to toElement, exclusive.
Object first()
Returns the first (lowest) element currently in this sorted set.
SortedSet headSet(Object toElement)
Returns a view of the portion of this set whose elements are strictly less than toElement.
Methods in TreeSet
SortedSet tailSet(Object fromElement)
Returns a view of the portion of this set whose elements are greater than or equal to
fromElement.

boolean remove(Object o)
Removes the specified element from this set if it is present.

Object last()
Returns the last (highest) element currently in this sorted set.

void clear()
Removes all of the elements from this set.
TreeSet Example
Review questions
• What are the two ways to iterate the elements of a collection?
• What is the difference between ArrayList and Vector classes in
collection framework?
• What is the difference between HashSet and HashMap classes in
collection framework?
• Discuss the features of TreeSet class.
• Describe Set Interface and various methods given by it.
• Differentiate between HashSet and TreeSet.
• Differentiate between PriorityQueue and ArrayDeque.
• Write a java program to show union and intersection of two set
collection.

You might also like