OopsWithJava-Unit-4-by-MultiAtoms
OopsWithJava-Unit-4-by-MultiAtoms
● Collection in Java
● Collection Framework in Java
● Hierarchy of Collection
Framework
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.
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.
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
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.
Iterator<T> iterator()
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’.
● 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.
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.
● 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
● 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.
● 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.
● 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:
● 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:
● 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.
● 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.
● 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.
● 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.
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.
● 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.
● 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.
● 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
● 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-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.
● 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.
● 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.
● 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.
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.
-> 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-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.
● 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
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