Unit 4 Notes OOPs with Java (BCS-403)
Unit 4 Notes OOPs with Java (BCS-403)
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:
Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Methods of Collection interface
There are many methods declared in the Collection interface. They are as follows:
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
There are only three methods in the Iterator interface. They are:
Iterable Interface
The 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.
1. Iterator<T> iterator()
It returns the iterator over the elements of type T.
Collection Interface
The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have. In other words,
we can say that the Collection interface builds the foundation on which the collection
framework depends.
Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll (
Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface.
List Interface
List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.
List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
There are various methods in List interface that can be used to insert, delete, and access the
elements from the list.
The classes that implement the List interface are given below.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to store the
duplicate element of different data types. The ArrayList class maintains the insertion order
and is non-synchronized. The elements stored in the ArrayList class can be randomly
accessed. Consider the following example.
import java.util.*;
class TestJavaCollection1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();//Creating arraylist
list.add("Ravi");//Adding object in arraylist
list.add("Vijay");
list.add("Ravi");
list.add("Ajay");
//Traversing list through Iterator
Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
LinkedList
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. In LinkedList, the manipulation is fast because no shifting is required.
import java.util.*;
public class TestJavaCollection2{
public static void main(String args[]){
LinkedList<String> al=new LinkedList<String>();
al.add("Ravi");
al.add("Vijay");
al.add("Ravi");
al.add("Ajay");
Iterator<String> itr=al.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to ArrayList. However, It
is synchronized and contains many methods that are not the part of Collection framework.
Consider the following example.
import java.util.*;
public class TestJavaCollection3{
public static void main(String args[]){
Vector<String> v=new Vector<String>();
v.add("Ayush");
v.add("Amit");
v.add("Ashish");
v.add("Garima");
Iterator<String> itr=v.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Amit
Ashish
Garima
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
import java.util.*;
public class TestJavaCollection4{
public static void main(String args[]){
Stack<String> stack = new Stack<String>();
stack.push("Ayush");
stack.push("Garvit");
stack.push("Amit");
stack.push("Ashish");
stack.push("Garima");
stack.pop();
Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ayush
Garvit
Amit
Ashish
Queue Interface
Queue interface maintains the first-in-first-out order. It can be defined as an ordered list that
is used to hold the elements which are about to be processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which implements the Queue interface.
There are various classes that implement the Queue interface, some of them are given below.
PriorityQueue
The PriorityQueue class implements the Queue interface. It holds the elements or objects
which are to be processed by their priorities. PriorityQueue doesn't allow null values to be
stored in the queue.
import java.util.*;
public class TestJavaCollection5{
public static void main(String args[]){
PriorityQueue<String> queue=new PriorityQueue<String>();
queue.add("Amit Sharma");
queue.add("Vijay Raj");
queue.add("JaiShankar");
queue.add("Raj");
System.out.println("head:"+queue.element());
System.out.println("head:"+queue.peek());
System.out.println("iterating the queue elements:");
Iterator itr=queue.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
queue.remove();
queue.poll();
System.out.println("after removing two elements:");
Iterator<String> itr2=queue.iterator();
while(itr2.hasNext()){
System.out.println(itr2.next());
}
}
}
Output:
head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj
Deque Interface
Deque interface extends the Queue interface. In Deque, we can remove and add the elements
from both the side. Deque stands for a double-ended queue which enables us to perform the
operations at both the ends.
ArrayDeque
ArrayDeque class implements the Deque interface. It facilitates us to use the Deque. Unlike
queue, we can add or delete the elements from both the ends.
ArrayDeque is faster than ArrayList and Stack and has no capacity restrictions.
import java.util.*;
public class TestJavaCollection6{
public static void main(String[] args) {
//Creating Deque and adding elements
Deque<String> deque = new ArrayDeque<String>();
deque.add("Gautam");
deque.add("Karan");
deque.add("Ajay");
//Traversing elements
for (String str : deque) {
System.out.println(str);
}
}
}
Output:
Gautam
Karan
Ajay
Set Interface
Set Interface in Java is present in java.util package. It extends the Collection interface. It
represents the unordered set of elements which doesn't allow us to store the duplicate items.
We can store at most one null value in Set. Set is implemented by HashSet, LinkedHashSet,
and TreeSet.
HashSet
HashSet class implements Set Interface. It represents the collection that uses a hash table for
storage. Hashing is used to store the elements in the HashSet. It contains unique items.
import java.util.*;
public class TestJavaCollection7{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//Traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Vijay
Ravi
Ajay
LinkedHashSet
LinkedHashSet class represents the LinkedList implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like HashSet, It also contains unique elements.
It maintains the insertion order and permits null elements.
import java.util.*;
public class TestJavaCollection8{
public static void main(String args[]){
LinkedHashSet<String> set=new LinkedHashSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Output:
Ravi
Vijay
Ajay
SortedSet Interface
SortedSet is the alternate of Set interface that provides a total ordering on its elements. The
elements of the SortedSet are arranged in the increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the natural ordering of the elements.
TreeSet
Java TreeSet class implements the Set interface that uses a tree for storage. Like HashSet,
TreeSet also contains unique elements. However, the access and retrieval time of TreeSet is
quite fast. The elements in TreeSet stored in ascending order.
import java.util.*;
public class TestJavaCollection9{
public static void main(String args[]){
//Creating and adding elements
TreeSet<String> set=new TreeSet<String>();
set.add("Ravi");
set.add("Vijay");
set.add("Ravi");
set.add("Ajay");
//traversing elements
Iterator<String> itr=set.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
Java LinkedHashSet Class
Java LinkedHashSet class is a Hashtable and Linked list implementation of the Set interface.
It inherits the HashSet class and implements the Set interface.
The LinkedHashSet class extends the HashSet class, which implements the Set interface. The
Set interface inherits Collection and Iterable interfaces in hierarchical order.
The LinkedHashSet class extends the HashSet class, which implements the Set interface. The
Set interface inherits Collection and Iterable interfaces in hierarchical order.
Let's see a simple example of the Java LinkedHashSet class. Here you can notice that the
elements iterate in insertion order.
FileName: LinkedHashSet1.java
import java.util.*;
class LinkedHashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
LinkedHashSet<String> set=new LinkedHashSet();
set.add("One");
set.add("Two");
set.add("Three");
set.add("Four");
set.add("Five");
Iterator<String> i=set.iterator();
while(i.hasNext())
{
System.out.println(i.next());
}
}
}
Output:
One
Two
Three
Four
Five
A set is used to provide a particular ordering on its element. The elements are ordered either
by using a natural ordering or by using a Comparator. All the elements which are inserted
into a sorted set must implement the Comparable interface.
The set's iterator will traverse the set in an ascending order. Several other operations are
provided in order to make best use of ordering. All the elements must be mutually
comparable.
Methods
comparator() Returns the comparator which is used to order the elements in the given
set. Also returns null if the given set uses the natural ordering of the
element.
first() Returns the first element from the current set.
headSet(E Returns a view of the portion of the given set whose elements are strictly
toElement) less than the toElement.
last() Returns the reverse order view of the mapping which present in the map.
spliterator() Returns a key-value mapping which is associated with the least key in the
given map. Also, returns null if the map is empty.
subSet(E Returns a key-value mapping which is associated with the greatest key
fromElement, E which is less than or equal to the given key. Also, returns null if the map is
toElement) empty.
tailSet(E Returns a view of the map whose keys are strictly less than the toKey.
fromElement)
Example 1
import java.util.SortedSet;
import java.util.TreeSet;
public class JavaSortedSetExample1 {
public static void main(String[] args) {
SortedSet set = new TreeSet();
// Add the elements in the given set.
set.add("Audi");
set.add("BMW");
set.add("Mercedes");
set.add("Baleno");
System.out.println("The list of elements is given as:");
for (Object object : set) {
System.out.println(object);
}
//Returns the first element
System.out.println("The first element is given as: " + set.first());
//Returns the last element
System.out.println("The last element is given as: " + set.last());
//Returns a view of the portion of the given set whose elements are strictly less than the
toElement.
System.out.println("The respective element is given as: " + set.headSet("Baleno"));
//Returns a view of the map whose keys are strictly less than the toKey.
System.out.println("The respective element is given as: " + set.tailSet("Audi"));
}
}
Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value
pair, where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the java.util package.
Points to remember
o Java HashMap contains values based on the key.
o Java HashMap contains only unique keys.
o Java HashMap may have one null key and multiple null values.
o Java HashMap is non synchronized.
o Java HashMap maintains no order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.
Let's see a simple example of HashMap to store key and value pair.
import java.util.*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
map.put(1,"Mango"); //Put elements in Map
map.put(2,"Apple");
map.put(3,"Banana");
map.put(4,"Grapes");
System.out.println("Iterating Hashmap...");
for(Map.Entry m : map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Java LinkedHashMap class:
Java LinkedHashMap class is Hashtable and Linked list implementation of the Map interface,
with predictable iteration order. It inherits HashMap class and implements the Map interface.
Points to remember
o Java LinkedHashMap contains values based on the key.
o Java LinkedHashMap contains unique elements.
o Java LinkedHashMap may have one null key and multiple null values.
o Java LinkedHashMap is non synchronized.
o Java LinkedHashMap maintains insertion order.
o The initial default capacity of Java HashMap class is 16 with a load factor of 0.75.
Constructor Description
LinkedHashMap() It is used to construct a default LinkedHashMap.
LinkedHashMap(int capacity) It is used to initialize a LinkedHashMap with the given capacity.
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the load factor.
loadFactor)
LinkedHashMap(int capacity, float It is used to initialize both the capacity and the load factor with specified ordering mod
loadFactor, boolean accessOrder)
LinkedHashMap(Map<? extends K,? It is used to initialize the LinkedHashMap with the elements from the given Map class
extends V> m)
hm.put(100,"Amit");
hm.put(101,"Vijay");
hm.put(102,"Rahul");
for(Map.Entry m:hm.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
Java Hashtable class
Java Hashtable class implements a hashtable, which maps keys to values. It inherits
Dictionary class and implements the Map interface.
Points to remember
o 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.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
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());
}
}
}
Sorting Algorithms
Sorting is the process of arranging the elements of an array so that they can be placed either
in ascending or descending order. For example, consider an array A = {A1, A2, A3, A4, ??
An }, the array is called to be in ascending order if element of A are arranged like A1 > A2 >
A3 > A4 > A5 > ? > An .
Consider an array;
int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 )
There are many techniques by using which, sorting can be performed. In this section of the
tutorial, we will discuss each method in detail.
Sorting Algorithms
Sorting algorithms are described in the following table along with the description.
SN Sorting Description
Algorithms
1 Bubble Sort It is the simplest sort method which performs sorting by repeatedly moving
the largest element to the highest index of the array. It comprises of
comparing each element to its adjacent element and replace them
accordingly.
2 Bucket Sort Bucket sort is also known as bin sort. It works by distributing the element
into the array also called buckets. In this sorting algorithms, Buckets are
sorted individually by using different sorting algorithm.
3 Comb Sort Comb Sort is the advanced form of Bubble Sort. Bubble Sort compares all the
adjacent values while comb sort removes all the turtle values or small values
near the end of the list.
4 Counting Sort It is a sorting technique based on the keys i.e. objects are collected according
to keys which are small integers. Counting sort calculates the number of
occurrence of objects and stores its key values. New array is formed by
adding previous key elements and assigning to objects.
5 Heap Sort In the heap sort, Min heap or max heap is maintained from the array
elements deending upon the choice and the elements are sorted by deleting
the root element of the heap.
6 Insertion Sort As the name suggests, insertion sort inserts each element of the array to its
proper place. It is a very simple sort method which is used to arrange the
deck of cards while playing bridge.
7 Merge Sort Merge sort follows divide and conquer approach in which, the list is first
divided into the sets of equal elements and then each half of the list is sorted
by using merge sort. The sorted list is combined again to form an elementary
sorted array.
8 Quick Sort Quick sort is the most optimized sort algorithms which performs sorting in
O(n log n) comparisons. Like Merge sort, quick sort also work by using divide
and conquer approach.
9 Radix Sort In Radix sort, the sorting is done as we do sort the names according to their
alphabetical order. It is the lenear sorting algorithm used for Inegers.
10 Selection Sort Selection sort finds the smallest element in the array and place it on the first
place on the list, then it finds the second smallest element in the array and
place it on the second place. This process continues until all the elements are
moved to their correct ordering. It carries running time O(n2) which is worst
than insertion sort.
11 Shell Sort Shell sort is the generalization of insertion sort which overcomes the
drawbacks of insertion sort by comparing elements separated by a gap of
several positions.
Java Comparable interface is used to order the objects of the user-defined class. This
interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements
on the basis of single data member only. For example, it may be rollno, name, age or
anything else.
public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
o positive integer, if the current object is greater than the specified object.
o negative integer, if the current object is less than the specified object.
o zero, if the current object is equal to the specified object.
1. String objects
2. Wrapper class objects
3. User-defined class objects
Collections class
Collections class provides static methods for sorting the elements of collections. If collection
elements are of Set or Map, we can use TreeSet or TreeMap. However, we cannot sort the
elements of List. Collections class provides methods for sorting the elements of List type
elements.
public void sort(List list): It is used to sort the elements of List. List elements must be of the
Comparable type
Let's see the example of the Comparable interface that sorts the list elements on the basis of
age.
File: Student.java
File: TestSort1.java
import java.util.*;
public class TestSort1{
public static void main(String args[]){
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
Collections.sort(al);
for(Student st:al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}
105 Jai 21
101 Vijay 23
106 Ajay 27
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.
An Advantage of the properties file
Recompilation is not required if the information is changed from a properties file: If any
information is changed from the properties file, you don't need to recompile the java class. It
is used to store information which is to be changed frequently.
Properties(Properties defaults) It creates an empty property list with the specified defaults.
Method Description
public void load(InputStream is) It loads data from the InputStream object
public void loadFromXML(InputStream in) It is used to load all of the properties represented by the XML
document on the specified input stream into this properties table.
public String getProperty(String key, String It searches for the property with the specified key.
defaultValue)
public void setProperty(String key, String value) It calls the put method of Hashtable.
public void list(PrintStream out) It is used to print the property list out to the specified output stream
public void list(PrintWriter out)) It is used to print the property list out to the specified output stream
public Enumeration<?> propertyNames()) It returns an enumeration of all the keys from the property list.
public Set<String> stringPropertyNames() It returns a set of keys in from property list where the key and its
corresponding value are strings.
public void store(Writer w, String comment) It writes the properties in the writer object.
public void store(OutputStream os, String It writes the properties in the OutputStream object.
comment)
public void storeToXML(OutputStream os, It writes the properties in the writer object for generating XML
String comment) document.
public void storeToXML(Writer w, String It writes the properties in the writer object for generating XML
comment, String encoding) document with the specified encoding.
To get information from the properties file, create the properties file first.
db.properties
1. user=system
2. password=oracle
Now, let's create the java class to read the data from the properties file.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
FileReader reader=new FileReader("db.properties");
System.out.println(p.getProperty("user"));
System.out.println(p.getProperty("password"));
}
}
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the java class.
That means no maintenance problem.
By System.getProperties() method we can get all the properties of the system. Let's create the
class that gets information from the system properties.
Test.java
import java.util.*;
import java.io.*;
public class Test {
public static void main(String[] args)throws Exception{
Properties p=System.getProperties();
Set set=p.entrySet();
Iterator itr=set.iterator();
while(itr.hasNext()){
Map.Entry entry=(Map.Entry)itr.next();
System.out.println(entry.getKey()+" = "+entry.getValue());
}
}
}
Output:
java.runtime.name = Java(TM) SE Runtime Environment
sun.boot.library.path = C:\Program Files\Java\jdk1.7.0_01\jre\bin
java.vm.version = 21.1-b02
java.vm.vendor = Oracle Corporation
java.vendor.url = http://java.oracle.com/