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

OopsWithJava-Unit-4-by-MultiAtoms

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

OopsWithJava-Unit-4-by-MultiAtoms

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

Multi Atoms Plus

Oops With Java


Unit-4
(Java Collections Framework)

Aktu 2nd Year Subject Code - (BCS 403)


Multi Atoms Plus

Syllabus Unit-4 OOPS WITH JAVA


Multi Atoms Plus

● Collection in Java
● Collection Framework in Java
● Hierarchy of Collection
Framework

Lecture-18 ● Iterator Interface


● Collection Interface
● List Interface
First Lecture of Unit-4 ● ArrayList
● LinkedList
● Vector
● Stack
Multi Atoms Plus

Collection in Java
A collection in Java is a single unit of objects, known as elements. The Java Collections
Framework provides a set of interfaces and classes to handle various types of
collections. Collections are used to store, retrieve, manipulate, and communicate
aggregate data.

Book is Single Object


Group of Books = Collection

Uses of Collections:
● Efficient memory usage
● Enhanced code readability
● Built-in sorting algorithms
Multi Atoms Plus

Framework?
A framework is a structured platform that provides a foundation of predefined classes,
methods, and tools to help developers build and manage software applications more
efficiently and effectively. It establishes a standard way to build and deploy
applications, offering reusable components and promoting best practices.

Set of classes & interfaces

Framework
Multi Atoms Plus
Introduction to the Collection Framework
● The Java Collections Framework is a comprehensive set of classes and interfaces
that provide a standardized way to manage groups of objects.
● It offers data structures such as lists, sets, queues, and maps, along with
algorithms for sorting, searching, and manipulating data.
● This framework simplifies development by providing reusable components,
enhancing code quality, and improving performance through well-optimized
implementations. Map

● Interfaces and its implementations


● Algorithm
List Queue
Sets
Multi Atoms Plus
Hierarchy of Collection Framework
Multi Atoms Plus

Iterable Interface
The Iterable Interface is a fundamental part of the Java Collections Framework and
provides the foundation for all collection types that can be iterated over using an
enhanced for loop (also known as the "for-each" loop) or an Iterator.

It is located in the java.lang package and is the root interface for all collection classes in
Java.

Core Method of the Iterable Interface:

Iterator<T> iterator()

Returns an Iterator over elements of type T.


Multi Atoms Plus

Iterator Interface
The Iterator Interface in Java is a part of the Java Collections Framework and provides
a way to traverse through the elements of a collection sequentially without exposing
the underlying structure of the collection.

It is an interface in the ‘java.util’ package and is widely used to iterate over the
elements of various collections like ‘List’, ‘Set’, and ‘Queue’.

Key Features of the Iterator Interface:

● Unified Interface for Collection Traversal: The Iterator provides a standard way to
traverse elements in a collection, making it easier to handle different types of
collections uniformly.
● Supports Removal: It allows the removal of elements from the underlying
collection during the iteration.
Multi Atoms Plus
Common Methods in the Iterator Interface:
1. hasNext()

Description: Returns true if there are more elements to iterate over; otherwise, it returns false.

1. next()

Description: Returns the next element in the iteration. Throws NoSuchElementException if there are no
more elements.

1. remove()

Description: Removes the last element returned by the next() method from the underlying collection.
This method can be called only once per call to next(). If remove() is called without calling next(), or if
remove() is called more than once for the same element, it will throw IllegalStateException.
Multi Atoms Plus
Iterator Example
Multi Atoms Plus
Collection Interface
The Collection Interface is the root interface of the Java Collections Framework. It represents a
group of objects, known as elements, and provides standard methods to manipulate these
elements.

Key Methods in the Collection Interface:

● boolean add(): Adds an element to the collection.


● boolean remove(): Removes a specified element.
● boolean contains(): Checks if the collection contains a specified element.
● int size(): Returns the number of elements in the collection.
● Iterator<E> iterator(): Returns an iterator over the elements.
● boolean isEmpty(): Checks if the collection is empty.
● void clear(): Removes all elements from the collection.

Subinterfaces and Implementations: The Collection interface is extended by more specific


interfaces like List, Set, and Queue, each providing more specialized methods.
Multi Atoms Plus
Collection Interface Example
Multi Atoms Plus
List Interface
The List Interface is a subinterface of the Collection interface in the Java Collections Framework.

It represents an ordered collection (also known as a sequence) where elements can be inserted, accessed,
and removed by their position (index) in the list.

The List interface allows duplicate elements and maintains the insertion order.

Key Characteristics of the List Interface:

● Ordered Collection: Elements are stored in a specific sequence, and each element can be accessed
by its index.
● Allows Duplicates: A List can contain multiple elements with the same value.
● Indexed Access: Elements can be accessed using their index, starting from 0.
Multi Atoms Plus
Key Methods in the List Interface: The List interface includes all methods from the Collection interface, and
adds several methods specific to lists:
1. void add(int index, E element)
Description: Inserts the specified element at the specified position in the list. Shifts the element currently at that
position (if any) and any subsequent elements to the right (adds one to their indices).
1. E get(int index)
Description: Returns the element at the specified position in the list.
1. E set(int index, E element)
Description: Replaces the element at the specified position in the list with the specified element.
1. E remove(int index)
Description: Removes the element at the specified position in the list. Shifts any subsequent elements to the left
(subtracts one from their indices).
1. int indexOf(Object o)
Description: Returns the index of the first occurrence of the specified element in the list, or -1 if the list does not
contain the element
Multi Atoms Plus

Implementations of the List Interface:


Several classes in the Java Collections Framework implement the List interface. Each
of these implementations has its characteristics and use cases:

● ArrayList
● LinkedList
● Vector
● Stack
Multi Atoms Plus
ArrayList class
The ArrayList class in Java is a resizable array implementation of the List interface. It provides a way to
dynamically store and access elements, allowing them to be added, removed, or accessed based on their index.

Key Features of ArrayList:

● Resizable Array: The size of an ArrayList can grow or shrink as elements are added or removed.
● Random Access: Elements can be accessed directly by their index, making retrieval operations fast (O(1)
time complexity).
● Allows Duplicates: ArrayList permits duplicate elements.
● Maintains Insertion Order: Elements are stored in the order they are added.

Commonly Used Constructors:

● ArrayList(): Creates an empty list with an initial capacity of 10.


● ArrayList(int initialCapacity): Creates an empty list with the specified initial capacity.
● ArrayList(Collection<? extends E> c): Creates a list containing the elements of the specified collection,
in the order they are returned by the collection's iterator.
Multi Atoms Plus
Multi Atoms Plus
LinkedList class
The LinkedList class in Java is a doubly-linked list implementation of the List and Deque interfaces. It
provides a way to store elements where each element is a node containing data and references to the next and
previous nodes. This allows efficient insertions and deletions at both ends of the list.

Key Features of LinkedList:

● Doubly-Linked List: Each node in the list contains references to both the next and previous nodes,
allowing traversal in both directions.
● Efficient Insertions/Deletions: Inserting or removing elements at the beginning or end of the list is more
efficient (O(1) time complexity) compared to ArrayList.
● Allows Duplicates: LinkedList permits duplicate elements.
● Maintains Insertion Order:

Commonly Used Constructors:

● LinkedList(): Creates an empty linked list.


● LinkedList(Collection<? extends E> c): Creates a linked list containing the elements of the specified
collection, in the order they are returned by the collection's iterator.
Multi Atoms Plus
Multi Atoms Plus
Vector Class
The Vector class in Java is a resizable array implementation of the List interface, similar to ArrayList, but with
some key differences. It is synchronized, meaning it is thread-safe, and is part of the legacy collection classes
that were later re-engineered to implement the List interface.

Key Features of Vector:

● Synchronized: All methods in Vector are synchronized, making it thread-safe but slower than ArrayList
in a single-threaded environment.
● Resizable Array: Like ArrayList, Vector can grow or shrink dynamically as elements are added or
removed.
● Allows Duplicates & Maintains Insertion Order:

Commonly Used Constructors:

● Vector() , Vector(int initialCapacity)


● Vector(int initialCapacity, int capacityIncrement)
● Vector(Collection<? extends E> c)
Multi Atoms Plus
Multi Atoms Plus
Stack class
The Stack class in Java is a subclass of Vector that implements a last-in, first-out (LIFO) stack of objects. It
provides methods to push elements onto the stack and pop them off, allowing the stack to operate as a LIFO
data structure.

Key Features of Stack:

● LIFO (Last-In, First-Out): The last element added to the stack is the first one to be removed.
● Extends Vector: Since Stack extends Vector, it inherits all the properties and methods of Vector, but it
also includes specific methods for stack operations.
● Thread-Safe: Like Vector, Stack is synchronized and therefore thread-safe, but this can lead to slower
performance in single-threaded environments.

Commonly Used Constructors:

● Stack(): Creates an empty stack.


Multi Atoms Plus
Commonly Used Methods:
1. push( item)
Pushes the specified element onto the top of the stack.
1. pop()
Removes and returns the element at the top of the stack.
1. peek()
Returns the element at the top of the stack without removing it.
1. boolean empty()
Returns true if the stack is empty, otherwise false.
1. int search(Object o)
Returns the 1-based position of the element on the stack. If the element is not found, it returns -1.
Multi Atoms Plus
Multi Atoms Plus
Queue Interface
The Queue interface in Java represents a collection designed for holding elements prior to processing. It
is part of the Java Collections Framework and provides methods to handle elements in a first-in, first-
out (FIFO) order.

Key Features of Queue:


● FIFO (First-In, First-Out): Elements are processed in the order they were added.
● Different Implementations: Common implementations include LinkedList, PriorityQueue, and
ArrayDeque.
● Support for Various Operations: Provides methods to insert, remove, and examine elements.
Multi Atoms Plus
Commonly Used
Methods:
● boolean add(E e): Inserts the specified element into the queue. Throws an exception if the
element cannot be added.

● boolean offer(E e): Inserts the specified element into the queue. Returns true if the
element was added successfully, false otherwise.

● E remove(): Removes and returns the element at the front of the queue. Throws an
exception if the queue is empty.

● E poll(): Removes and returns the element at the front of the queue. Returns null if the
queue is empty.

● E peek(): Retrieves, but does not remove, the element at the front of the queue. Returns
null if the queue is empty.

● E element(): Retrieves, but does not remove, the element at the front of the queue. Throws
an exception if the queue is empty.
Multi Atoms Plus
Multi Atoms Plus
PriorityQueue class
The PriorityQueue class in Java is an implementation of the Queue interface that orders its elements
according to their natural ordering or by a Comparator provided at queue construction time. Unlike
other queue implementations, PriorityQueue does not guarantee FIFO order; instead, it prioritizes
elements based on their priority.

Commonly Used Constructors:

● PriorityQueue(): Creates a priority queue with the default initial capacity (11) and natural ordering
of elements.
● PriorityQueue(int initialCapacity, Comparator<? super E> comparator): Creates a priority queue
with the specified initial capacity and ordering determined by the specified comparator.
Multi Atoms Plus
Multi Atoms Plus
Multi Atoms Plus
Set Interface
The Set interface in Java represents a collection that does not allow duplicate elements. It is part of the
Java Collections Framework and extends the Collection interface. Implementations of the Set interface
include HashSet, LinkedHashSet, and TreeSet.

Key Features of Set:

● No Duplicates: Sets do not allow duplicate elements. Adding a duplicate element will have no
effect.
● Unordered or Ordered: Some implementations (like HashSet) do not guarantee the order of
elements, while others (like TreeSet) maintain a specific order.
● Efficient Operations: The Set interface provides efficient methods for adding, removing, and
checking the presence of elements.

All the methods same as in this method added : int hashCode(): Returns the hash code value for the set.
Multi Atoms Plus
HashSet class
The HashSet class in Java is an implementation of the Set interface that uses a hash table for storage. It
is part of the Java Collections Framework and provides a collection that does not allow duplicate
elements and does not guarantee any specific order of elements.

Key Features of HashSet:

No Duplicate Elements: Ensures that no duplicate elements are added to the set.

Unordered: Does not maintain any order of elements. The order of elements is not predictable.

Not Synchronized: HashSet is not synchronized, so it is not thread-safe. Use Collections.synchronizedSet


if thread safety is required.
Multi Atoms Plus
Multi Atoms Plus
LinkedHashSet Class
The LinkedHashSet class in Java is an implementation of the Set interface that combines the features of
HashSet and LinkedList. It maintains the insertion order of elements while providing the performance
characteristics of a hash table.

Key Features of LinkedHashSet:

● Insertion Order: Maintains the order of elements as they were inserted.


● No Duplicates: Does not allow duplicate elements.
● Efficient Operations: Provides O(1) time complexity for add, remove, and contains
operations, similar to HashSet.
● Linked List Structure: Uses a doubly linked list to maintain the order of elements
Multi Atoms Plus
Multi Atoms Plus
SortedSet interface
The SortedSet interface in Java is a subinterface of Set that provides a total ordering on its elements. It
extends the Set interface to handle sorted sets, ensuring that the elements are maintained in a specific
order.

Key Features of SortedSet:

● Ordering: Elements in a SortedSet are sorted according to their natural ordering or by a specified
comparator.
● Subsets: Provides methods to view subsets of the set, which are themselves sorted.
Multi Atoms Plus
Commonly Used
Methods:
● Comparator<? super E> comparator(): Returns the comparator used to sort the set, or null
if the set is sorted according to natural ordering.

● E first(): Returns the first (lowest) element in the set.


● E last(): Returns the last (highest) element in the set.

● SortedSet<E> headSet(E toElement): Returns a view of the portion of the set whose
elements are strictly less than toElement.

● SortedSet<E> tailSet(E fromElement): Returns a view of the portion of the set whose
elements are greater than or equal to fromElement.

● SortedSet<E> subSet(E fromElement, E toElement): Returns a view of the portion of the


set whose elements range from fromElement, inclusive, to toElement, exclusive.
Multi Atoms Plus
TreeSet class
The TreeSet class in Java is a collection that implements the NavigableSet interface, which extends
SortedSet. It uses a Red-Black tree to store elements, ensuring that the elements are sorted and that
operations like addition, removal, and lookup are efficient.

Key Features of TreeSet:

● Sorted Order: Maintains elements in a sorted order, either by their natural ordering or by a
custom comparator.
● No Duplicates: Does not allow duplicate elements.
● Efficient Operations: Provides O(log n) time complexity for basic operations such as add,
remove, and contains.
Multi Atoms Plus
Multi Atoms Plus

Syllabus Unit-4 OOPS WITH JAVA


Multi Atoms Plus

● Map Interface
● HashMap Class
● LinkedHashMap Class

Lecture-20 ●

TreeMap Class
Hashtable Class
● Sorting
Third Lecture of Unit-4 ● Comparable Interface
● Comparator Interface
● Properties Class in Java.
Multi Atoms Plus
Multi Atoms Plus
Map Interface
The Map interface in Java represents a collection of key-value pairs, where each key is associated with
exactly one value. It does not extend the Collection interface. The Map interface provides a way to store
data in a key-value pair format, where you can efficiently retrieve, update, and delete values based on
their keys.

Key Features of Map:

● Key-Value Pairs: Maps store data as key-value pairs, where each key is
unique and maps to a single value.
● No Duplicate Keys: Keys must be unique. If a key is duplicated, the new
value will replace the old value.
● Efficient Operations: Provides efficient methods for adding, removing, and
accessing key-value pairs.
Multi Atoms Plus
Commonly Used
Methods:
● V put(K key, V value): Associates the specified value with the specified key in the map. If
the map previously contained a mapping for the key, the old value is replaced.

● V get(Object key): Returns the value to which the specified key is mapped, or null if the
map contains no mapping for the key.

● V remove(Object key): Removes the mapping for the specified key from the map if
present.

● boolean containsKey(Object key): Returns true if the map contains a mapping for the
specified key.

● boolean containsValue(Object value): Returns true if the map maps one or more keys to
the specified value.

● void clear(): Removes all mappings from the map.


Multi Atoms Plus
HashMap class
The HashMap class in Java is a widely-used implementation of the Map interface that stores key-value
pairs in a hash table. It allows for efficient retrieval, insertion, and deletion of elements, and does not
guarantee the order of its elements.

Key Features of HashMap:

● Hash Table: Uses a hash table to store the key-value pairs, which provides constant-time
complexity for basic operations such as add, remove, and contains, assuming a good hash
function.
● No Guaranteed Order: Does not guarantee any specific order of its elements.
Multi Atoms Plus
Multi Atoms Plus
LinkedHashMap Class
The LinkedHashMap class in Java is a hash table and linked list implementation of the Map interface. It
maintains a doubly-linked list running through all of its entries to maintain the insertion order. This
class combines the hash table's efficiency with a linked list's predictable iteration order.

Key Features of LinkedHashMap:

● Insertion Order: Maintains the order of elements based on their insertion sequence.
● No Duplicate Keys: Does not allow duplicate keys. If a key is re-inserted, the old value is
replaced.
● Performance: Provides constant-time performance for basic operations like get and put, similar
to HashMap.
Multi Atoms Plus
Multi Atoms Plus
TreeMap Class
The TreeMap class in Java is an implementation of the NavigableMap interface that uses a Red-Black
tree to store its key-value pairs. It provides a way to store and access key-value pairs in a sorted order
based on the natural ordering of its keys or by a specified comparator.

Key Features of TreeMap:

● Sorted Order: Stores keys in a sorted order (ascending by default). The order is maintained using
a Red-Black tree.
● Key Comparison: Keys are compared using their natural ordering or a custom Comparator if one
is provided.
● Performance: Provides O(log n) time complexity for basic operations like add, remove, and
contains.
Multi Atoms Plus
Multi Atoms Plus
Hashtable Class
The Hashtable class in Java is a legacy class that implements the Map interface using a hash table. It
provides a way to store key-value pairs, similar to HashMap, but with some important differences in
behavior and performance characteristics.

Key Features of Hashtable:

● Synchronization: Hashtable is synchronized, making it thread-safe. Multiple threads can access a


Hashtable concurrently without the need for additional synchronization.
● No Null Keys or Values: Does not allow null keys or values. Attempting to insert a null key or
value will result in a NullPointerException.
● Legacy Class: Hashtable is considered a legacy class and is part of the original version of Java. It
is retained for backward compatibility but is generally replaced by HashMap in modern code.
● Performance: Due to its synchronization, Hashtable can be slower than HashMap in single-
threaded or unsynchronized environments.
Multi Atoms Plus
Multi Atoms Plus
Sorting
In Java, sorting can be applied to collections and arrays. The Collections class provides static methods
for sorting lists, while arrays can be sorted using the Arrays class. Sorting is typically done in ascending
order, but you can customize the sort order using comparators. Here’s an overview of sorting in Java:

Sorting Lists

1. Using Collections.sort(): The Collections.sort() method is used to sort a List in ascending order. It
uses the natural ordering of elements or a custom Comparator.
Multi Atoms Plus
Multi Atoms Plus
Sorting Arrays

Using Arrays.sort(): The Arrays.sort() method is used to sort arrays. It provides overloads for different
data types and can also sort arrays using a custom Comparator for objects.
Multi Atoms Plus
Comparable and Comparator interfaces
The Comparable and Comparator interfaces in Java are essential for sorting and ordering objects in
collections. They provide a standardized way to define and control how objects are compared and
ordered, which is crucial for many operations in programming.

Comparable Interface

● The Comparable interface in Java is used to define the natural ordering of objects of a class. It
allows objects of the class to be compared to one another, which is useful for sorting and
ordering. Located in java.lang package
● int compareTo(T o): Compares the current object with the specified object for order.

Returns: -> A negative integer if the current object is less than the specified object.

-> Zero if the current object is equal to the specified object.

-> A positive integer if the current object is greater than the specified object.
Multi Atoms Plus

Output
Multi Atoms Plus

Comparator Interface

● The Comparator interface is used to define custom ordering of objects. It allows you to specify
multiple different sorting orders, unlike Comparable, which allows only one natural ordering.
● Located in java.util package
● int compare(T o1, T o2): Compares two objects for order.

Usage: Used when objects need to be sorted in ways other than their natural ordering, or when the class
does not implement Comparable.
Multi Atoms Plus

Output:
Multi Atoms Plus
Properties Class in Java
The Properties class in Java is part of the java.util package and extends the Hashtable class. It is used to
maintain a set of key-value pairs where both the keys and values are strings. The Properties class is
commonly used for configuration settings and managing application properties.

Key Features of Properties Class

● Key-Value Storage: Stores properties in key-value pairs where both keys and values are strings.
● Persistence: Supports saving and loading properties from files or streams.
● Inheritance: Can inherit properties from another Properties object, allowing for default values.

Properties properties = new Properties();


Multi Atoms Plus
Common Methods:
1. Loading Properties

● void load(InputStream inStream): Loads properties from an input stream (e.g., file).
● void load(Reader reader): Loads properties from a reader (e.g., text file).

2. Storing Properties

● void store(OutputStream outStream, String comments): Saves properties to an output


stream.
● void store(Writer writer, String comments): Saves properties to a writer.

3. Accessing Properties

● String getProperty(String key): Retrieves the value associated with the specified key.
● String setProperty(String key, String value): Sets the value associated with the specified
key.
Multi Atoms Plus

Output:
Multi Atoms Plus

Unit-4 Completed
Multi Atoms Plus

Thank You
Subscribe Multi Atoms & Multi Atoms Plus

For Notes Join Telegram Channel

You might also like