Unit 4 OOPwithjava
Unit 4 OOPwithjava
Unit 4
Lecture 28
Unit 4
Lecture 29
Example:
// ArrayList declaration and initialization to store integers
ArrayList<Integer> arrayList = new ArrayList<>();
// Adding elements to ArrayList
arrayList.add(10);
Java ArrayList
• Java ArrayList class uses a dynamic array for
storing the elements.
• It is like an array, but there is no size limit.
• We can add or remove elements anytime.
• So, it is much more flexible than the traditional
array.
• It is found in the java.util package.
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 30
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 31
Constructor Description
Unit 4
Lecture 32
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
// Creating a TreeSet
TreeSet<Integer> numbers = new TreeSet<>();
// Adding elements to the TreeSet numbers.add(5);
numbers.add(2);
numbers.add(8);
numbers.add(1);
numbers.add(3); System.out.println("TreeSet of numbers: " +
numbers);
// Output: TreeSet of numbers: [1, 2, 3, 5, 8]
Example
Unit 4
Lecture 33
Unit 4
Lecture 34
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 35
Unit 4
Lecture 36
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
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