Unit 4 Notes
Unit 4 Notes
Unit 4
Lecture 28
Lecture 28
• Collection in Java
• Collection Framework in Java
• Hierarchy of Collection Framework
• Iterator Interface
• Collection Interface
• List Interface
• ArrayList
• LinkedList
Collection in Java
• The Collection in Java is a framework that
provides an architecture to store and manipulate
the group of objects.
• Java Collections can achieve all the operations
that we perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
• In Java, collections are part of the Java Collections
Framework (JCF), which is a unified architecture for
representing and manipulating groups of objects. The
JCF provides several interfaces and classes that
implement different types of collections, such as lists,
sets, queues, and maps.
Why use collections instead of arrays?
Arrays in Java have several limitations:
Fixed Size: Once an array is created, its size cannot be changed.
Collections, however, can grow or shrink dynamically as needed.
Type Safety: Collections can enforce type safety using generics,
reducing runtime errors related to type casting.
Utility Methods: Collections provide various utility methods for
common operations like searching, sorting, and manipulating
data.
Performance: Collections are optimized for performance with
various implementations for different use cases (e.g., fast random
access, quick insertion/deletion, etc.).
Benefits of using JCF
Reusability: Provides reusable data structures and
algorithms.
Interoperability: Allows different types of collections to
work together seamlessly.
Performance: Offers various implementations
optimized for different performance needs.
Flexibility: Supports dynamic resizing and allows
collections to grow and shrink as needed.
Type Safety: Uses generics to ensure type safety at
compile time.
Hierarchy of the Collection Framework in Java
Hierarchy of Collection Framework
Underneath Collection, we have three main
interfaces:
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.
Iterator interface
Iterator interface provides the facility of iterating the
elements in a forward direction only.
Methods of Iterator interface
No. Method Description
1 public boolean It returns true if the iterator has more
hasNext() elements otherwise it returns false.
3) An ArrayList class can act as a list only LinkedList class can act as a list and
because it implements List only. queue both because it implements List
and Deque interfaces.
Unit 4
Lecture 29
Lecture 30
• Vector
• Stack
• Queue Interface
Vector
•Vector is a class that implements a dynamic
array.
•It is similar to ArrayList, but it is
synchronized, making it thread-safe.
•However, this synchronization can impact
performance, so ArrayList is generally
preferred unless synchronization is required.
Vector is similar to the ArrayList, but with two
differences-
1. Vector is synchronized.
2. Java Vector contains many legacy
methods that are not the part of a
collections framework.
Java Vector Constructors
SN Constructor Description
import java.util.Stack;
public class StackExample {
public static void main(String[] args) {
Stack<String> stack = new Stack<>();
// Pushing elements onto the stack
stack.push("Java");
stack.push("Python");
stack.push("C++");
// Peeking at the top element of the stack
Example: Part: 2
boolean It is used to insert the specified element into this deque and
add(object) return true upon success.
boolean It is used to insert the specified element into this deque.
offer(object)
Object remove() It is used to retrieve and removes the head of this deque.
Object poll() It is used to retrieve and removes the head of this deque, or
returns null if this deque is empty.
Object element() It is used to retrieve, but does not remove, the head of this
deque.
Object peek() It is used to retrieve, but does not remove, the head of this
deque, or returns null if this
deque is empty.
bject peekFirst() The method returns the head element of the deque. The
method does not remove any element from the deque.
Null is returned by this method, when the deque is empty.
Object peekLast() The method returns the last element of the deque. The
method does not remove any element from the deque.
Null is returned by this method, when the deque is empty.
Boolean offerFirst(e) Inserts the element e at the front of the queue. If the
insertion is successful, true is returned; otherwise, false.
Object offerLast(e) Inserts the element e at the tail of the queue. If the
insertion is successful, true is returned; otherwise, false.
Deque<String> deque=new ArrayDeque<String>();
deque.offer("arvind");
deque.offer("vimal");
deque.add("mukul");
deque.offerFirst("jai");
System.out.println("After offerFirst Traversal...");
for(String s:deque)
{
System.out.println(s);
}
Output
After offerFirst Traversal...
jai
arvind
vimal
mukul
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 4
Lecture 30
Lecture 30
• Set Interface
• HashSet
• LinkedHashSet
• SortedSet Interface
• TreeSet,
Set Interface
• The set is an interface available in the java.util
package.
• The set interface extends the Collection interface.
An unordered collection or list in which duplicates
are not allowed is referred to as a collection
interface.
• The set interface is used to create the
mathematical set.
• The set interface use collection interface's
methods to avoid the insertion of the same
elements. SortedSet and NavigableSet are two
interfaces that extend the set implementation.
Example
import java.util.*;
public class setExample{
public static void main(String[] args)
{
// creating LinkedHashSet using the Set
Set<String> data = new LinkedHashSet<String>();
data.add("Java");
data.add("Set");
data.add("Example");
data.add("Set");
System.out.println(data);
}
}
Operations on the Set Interface
• On the Set, we can perform all the basic
mathematical operations like intersection, union
and difference.
• two sets, i.e.,
set1 = [22, 45, 33, 66, 55, 34, 77]
set2 = [33, 2, 83, 45, 3, 12, 55]
Intersection: The intersection operation returns all
those elements which are present in both the set.
The intersection of set1 and set2 will be [33, 45, 55].
• Union: The union operation returns all the
elements of set1 and set2 in a single set, and
that set can either be set1 or set2. The union of
set1 and set2 will be [2, 3, 12, 22, 33, 34, 45,
55, 66, 77, 83].
• Difference: The difference operation deletes
the values from the set which are present in
another set. The difference of the set1 and set2
will be [66, 34, 22, 77].
• In set, addAll() method is used to perform the
union, retainAll() method is used to perform
the intersection and removeAll() method is
used to perform difference.
Java HashSet
• Java HashSet class is used to
create a collection that uses a
hash table for storage.
• It inherits the Abstract Set class
and implements Set interface.
important points about Java HashSet class are:
• HashSet stores the elements by using a
mechanism called hashing.
• HashSet contains unique elements only.
• HashSet allows null value.
• HashSet class is non synchronized.
• HashSet doesn't maintain the insertion order.
Here, elements are inserted on the basis of their
hashcode.
• HashSet is the best approach for search
operations.
• The initial default capacity of HashSet is 16.
Constructors of Java HashSet class
1) HashSet() It is used to construct a default HashSet.
2) HashSet(int capacity) It is used to initialize the capacity
of the hash set to the given integer value capacity. The
capacity grows automatically as elements are added to
the HashSet.
3) HashSet(int capacity, float loadFactor) It is used to
initialize the capacity of the hash set to the given integer
value capacity and the specified load factor.
Methods of Java HashSet class
add(E e) It is used to add the specified element to this set if it is not
already present.
Constructor Description
Unit 4
Lecture 31
Lecture 31
• Map Interface
• HashMap Class
• LinkedHashMap Class
• TreeMap Class
• Hashtable Class
Map Interface
The Map interface in Java is part of the java.util package and
represents a collection of key-value pairs. It provides a way to
store and retrieve values using keys, similar to a dictionary or an
associative array in other programming languages.
Key-Value Pairs: A Map stores data as key-value pairs, where
each key is unique and maps to a specific value. Keys are used to
access and retrieve the associated values.
Unique Keys: The keys in a Map must be unique. Attempting to
insert a duplicate key will replace the value associated with the
existing key.
Null Values: A Map can store null values, but the behavior for
null keys depends on the specific implementation.
Map Interface
Implementations: The Map interface has several
concrete implementations in Java, including
HashMap, TreeMap, LinkedHashMap, and
ConcurrentHashMap.
Ordering: Some Map implementations, like TreeMap,
maintain an ordering of the keys, while others, like
HashMap, do not guarantee any specific order.
Common Methods: The Map interface provides
various methods for working with key-value pairs,
such as put(), get(), containsKey(), containsValue(),
remove(), size(), keySet(), values(), and entrySet().
import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// Creating a HashMap
Map<String, Integer> studentAges = new HashMap<>();
// Adding key-value pairs to the Map
studentAges.put("Alice", 20);
studentAges.put("Bob", 22);
studentAges.put("Charlie", 19);
// Retrieving a value using its key
int aliceAge = studentAges.get("Alice"); System.out.println("Alice's
age: " + aliceAge); // Output: Alice's age: 20
HashMap Class
➢HashMap is one of the most commonly used
implementations of the Map interface in Java.
➢It stores key-value pairs in a hash table data
structure, providing constant-time performance for
basic operations like get(), put(), and remove() on
average.
Hash Table Implementation: HashMap internally
uses a hash table to store its key-value pairs. The hash
table is an array of buckets, where each bucket can
hold one or more key-value pairs.
HashMap Class
Null Keys and Values: HashMap allows one null key and any
number of null values.
No Ordering: HashMap does not maintain any specific order
of the key-value pairs. The order in which elements are
returned by the iterator is not guaranteed to be the same as the
insertion order.
Performance: Basic operations like get(), put(), and remove()
have constant-time performance on average, assuming a good
hash function and a properly sized hash table.
However, in the worst case (e.g., when all keys hash to the
same bucket), the performance can degrade to linear
time.Iterators: HashMap provides iterators to traverse the keys,
values, or key-value pairs through the keySet(), values(), and
entrySet() methods, respectively. The order of iteration is not
guaranteed.
Example
Maintains insertion
Order No guaranteed order
order
Slightly slower due to
Performance Slightly faster
ordering
More memory
Memory Usage Less memory
(maintains links)
When insertion order
Use Case General purpose map
matters
void putAll(Map<? extends It is used to copy all the key-value pair from one
K,? extends V> map) map to another map.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean containsKey(Object It returns true if the map contains a mapping for the
key) specified key.
V get(Object key) It is used to return the value to which the map maps the
specified key.
V remove(Object key) It removes the key-value pair of the specified key from the
map.
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Difference between HashMap and
TreeMap
HashMap TreeMap
1) HashMap can contain one null TreeMap cannot contain any null
key. key.
2) HashMap maintains no order. TreeMap maintains ascending
order.
Hashtable Class
The Hashtable class in Java is a thread-safe
implementation of the Map interface.
It stores key-value pairs in a hash table data
structure, providing constant-time performance
for basic operations such as get() and put() on
average.
Important Points
• A Hashtable is an array of a list. Each list is known as
a bucket. The position of the bucket is identified by
calling the hashcode() method. A Hashtable
contains values based on the key.
• Java Hashtable class contains unique elements.
• Java Hashtable class doesn't allow null key or value.
• Java Hashtable class is synchronized.
• The initial default capacity of Hashtable class is 11
whereas loadFactor is 0.75.
Hashtable Class Features
• Thread-Safety: Hashtable is synchronized, which
means that all methods are thread-safe and can be
safely accessed by multiple threads concurrently.
This thread-safety comes at the cost of reduced
performance compared to non-synchronized
collections like HashMap.
• Null Keys and Values: Hashtable does not allow
null keys or null values. Attempting to insert a null
key or value will result in a NullPointerException.
• Underlying Data Structure: Hashtable uses a hash
table data structure to store the key-value pairs. It
uses an array of buckets, where each bucket holds a
linked list of key-value pairs that have the same hash
code.
Hashtable Class Features
• Load Factor and Rehashing: Hashtable has a default load
factor of 0.75, which means that when the number of
elements in the Hashtable exceeds 75% of its capacity, it
automatically increases its capacity and rehashes all the
existing elements.
• Iteration Order: Hashtable does not maintain the insertion
order of the elements. The elements are traversed in an
arbitrary order during iteration.
• Performance: The get(), put(), and remove() operations in
Hashtable have an average time complexity of O(1) when the
hash function distributes the elements properly. However, in
the worst-case scenario (when all elements hash to the same
bucket), the time complexity degrades to O(n), where n is the
number of elements.
Constructors of Java Hashtable class
Constructor Description
Hashtable() It creates an empty hashtable
having the initial default
capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter
and creates a hash table that
contains a specified initial
capacity.
Hashtable(int capacity, float It is used to create a hash table
loadFactor) having the specified initial
capacity and loadFactor.
Methods of Java Hashtable class
V put(K key, V value) It inserts the specified value with the
specified key in the hash table.
void putAll(Map<? extends K,? extends It is used to copy all the key-value pair
V> t)) from map to hashtable.
V putIfAbsent(K key, V value) If the specified key is not already
associated with a value (or is mapped to
null) associates it with the given value
and returns null, else returns the
current value.
boolean remove(Object key, Object It removes the specified values with the
value) associated specified keys from the
hashtable.
V replace(K key, V value) It replaces the specified value for a
specified key.
Example 1
import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,S
tring>();
hm.put(100,"Amit");
hm.put(102,"Ravi");
hm.put(101,"Vijay");
hm.put(103,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Example 2
import java.util.*;
public class Hashtable2 {
public static void main(String args[]) {
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
System.out.println("Before remove: "+ map);
// Remove value for key 102
map.remove(102);
System.out.println("After remove: "+ map);
}
}
Example 3
import java.util.*;
class Hashtable3{
public static void main(String args[]){
Hashtable<Integer,String> map=new Hashtable<Integer,String>();
map.put(100,"Amit");
map.put(102,"Ravi");
map.put(101,"Vijay");
map.put(103,"Rahul");
//Here, we specify the if and else statement as arguments of the
method
System.out.println(map.getOrDefault(101, "Not Found"));
System.out.println(map.getOrDefault(105, "Not Found"));
}
}
Object Oriented Programming with Java
(Subject Code: BCS-403)
Unit 4
Lecture 32
Lecture 32
• Sorting
• Comparable Interface
• Comparator Interface
• Properties Class in Java
Sorting in Java Collection Framework
Sorting in Java's Collection Framework is a crucial
aspect of organizing and manipulating data. Java
provides various sorting algorithms and utilities to sort
collections of elements based on different criteria.
The Java Collection Framework provides several
methods for sorting collections, primarily through
the Collections and Arrays classes.
These methods utilize Timsort, a highly efficient
sorting algorithm.
Sorting Algorithms
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
Comparator interface
• Java Comparator interface is used to order the
objects of a user-defined class.
• This interface is found in java.util package and
contains 2 methods compare(Object obj1,Object
obj2) and equals(Object element).
• It provides multiple sorting sequences, i.e., you
can sort the elements on the basis of any data
member, for example, rollno, name, age or
anything else.
Properties Class in Java
• The properties object contains key and value pair
both as a string.
• The java.util.Properties class is the subclass of
Hashtable.
• It can be used to get property value based on the
property key.
• The Properties class provides methods to get data
from the properties file and store data into the
properties file.
• Moreover, it can be used to get the properties of a
system.
Features of Properties Class in Java
Inheritance: Properties extends the Hashtable class,
inheriting its thread-safe behavior and the ability to store
key-value pairs. However, both keys and values in a
Properties object are treated as Strings.
Loading Properties: Properties objects can be loaded
from various sources, including files, input streams, and
readers. The load() method reads properties from an input
stream in a simple line-oriented format (key=value).
Storing Properties: The store() method can write the
contents of a Properties object to an output stream or
writer in a format suitable for loading into a Properties
object.
Constructors of Properties class
Method Description
Properties() It creates an empty property
list with no default values.
Properties(Properties defaults) It creates an empty property
list with the specified defaults.
Methods of Properties class
Method Description