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

Unit 4 Notes OOPs with Java (BCS-403)

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Set, List, Queue, and their implementations like ArrayList, LinkedList, and HashSet. It discusses the methods available in the Collection interface, Iterator interface, and specific classes, highlighting their functionalities and use cases. Additionally, it explains the hierarchy and characteristics of different collection types, including their instantiation and examples of usage.

Uploaded by

gamerpurrple.1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Unit 4 Notes OOPs with Java (BCS-403)

The document provides an overview of the Java Collections Framework, detailing its architecture for storing and manipulating groups of objects through various interfaces and classes such as Set, List, Queue, and their implementations like ArrayList, LinkedList, and HashSet. It discusses the methods available in the Collection interface, Iterator interface, and specific classes, highlighting their functionalities and use cases. Additionally, it explains the hierarchy and characteristics of different collection types, including their instantiation and examples of usage.

Uploaded by

gamerpurrple.1
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Unit-4

Java Collections Framework

Collections 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 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).

What is Collection in Java

A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and manipulating a
group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

Hierarchy of Collection Framework

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:

No. Method Description


1 public boolean add(E e) It is used to insert an element in this collection.
2 public boolean addAll(Collection<? It is used to insert the specified collection elements in
extends E> c) the invoking collection.
3 public boolean remove(Object It is used to delete an element from the collection.
element)
4 public boolean It is used to delete all the elements of the specified
removeAll(Collection<?> c) collection from the invoking collection.
5 default boolean It is used to delete all the elements of the collection
removeIf(Predicate<? super E> filter) that satisfy the specified predicate.
6 public boolean It is used to delete all the elements of invoking
retainAll(Collection<?> c) collection except the specified collection.
7 public int size() It returns the total number of elements in the
collection.
8 public void clear() It removes the total number of elements from the
collection.
9 public boolean contains(Object It is used to search an element.
element)
10 public boolean It is used to search the specified collection in the
containsAll(Collection<?> c) collection.
11 public Iterator iterator() It returns an iterator.
12 public Object[] toArray() It converts collection into array.
13 public <T> T[] toArray(T[] a) It converts collection into array. Here, the runtime
type of the returned array is that of the specified
array.
14 public boolean isEmpty() It checks if collection is empty.
15 default Stream<E> parallelStream() It returns a possibly parallel Stream with the
collection as its source.
16 default Stream<E> stream() It returns a sequential Stream with the collection as
its source.
17 default Spliterator<E> spliterator() It generates a Spliterator over the specified elements
in the collection.
18 public boolean equals(Object It matches two collections.
element)
19 public int hashCode() It returns the hash code number of the collection.

Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator interface. They are:

NO. METHOD DESCRIPTION


1 public boolean It returns true if the iterator has more elements otherwise it
hasNext() returns false.
2 public Object next() It returns the element and moves the cursor pointer to the next
element.
3 public void remove() It removes the last elements returned by the iterator. It is less
used.

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.

It contains only one abstract method. i.e.,

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.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new 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.

Consider the following example.

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.

Consider the following example.

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.

Queue interface can be instantiated as:

1. Queue<String> q1 = new PriorityQueue();


2. Queue<String> q2 = new ArrayDeque();

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.

Consider the following example.

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.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

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.

Consider the following example.

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.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

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.

Consider the following example.

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.

Consider the following example.

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.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

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.

Consider the following example:

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 important points about the Java LinkedHashSet class are:

o Java LinkedHashSet class contains unique elements only like HashSet.


o Java LinkedHashSet class provides all optional set operations and permits null
elements.
o Java LinkedHashSet class is non-synchronized.
o Java LinkedHashSet class maintains insertion order.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface. The
Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

Hierarchy of LinkedHashSet class

The LinkedHashSet class extends the HashSet class, which implements the Set interface. The
Set interface inherits Collection and Iterable interfaces in hierarchical order.

LinkedHashSet Class Declaration

Let's see the declaration for java.util.LinkedHashSet class.

Constructors of Java LinkedHashSet Class


Constructor Description
HashSet() It is used to construct a default HashSet.
HashSet(Collection c) It is used to initialize the hash set by using the elements of the
collection c.
LinkedHashSet(int capacity) It is used to initialize the capacity of the linked hash set to the given
integer value capacity.
LinkedHashSet(int capacity, It is used to initialize both the capacity and the fill ratio (also called
float fillRatio) load capacity) of the hash set from its argument.

Java LinkedHashSet Example

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

Java SortedSet<E> interface

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.

Hierarchy of HashMap class

As shown in the above figure, HashMap class extends AbstractMap class and implements
Map interface.

HashMap class declaration

Let's see the declaration for java.util.HashMap class.

1. public class HashMap<K,V> extends AbstractMap<K,V> implements Map<K,V>, Cloneab


le, Serializable

HashMap class Parameters

Let's see the Parameters for java.util.HashMap class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.

Constructors of Java HashMap class


Constructor Description
HashMap() It is used to construct a default HashMap.
HashMap(Map<? extends K,? It is used to initialize the hash map by using the elements of the
extends V> m) given Map object m.
HashMap(int capacity) It is used to initializes the capacity of the hash map to the given
integer value, capacity.
HashMap(int capacity, float It is used to initialize both the capacity and load factor of the
loadFactor) hash map by using its arguments.

Methods of Java HashMap class


Method Description
void clear() It is used to remove all of the mappings from this map.
boolean isEmpty() It is used to return true if this map contains no key-value
mappings.
Object clone() It is used to return a shallow copy of this HashMap
instance: the keys and values themselves are not cloned.
Set entrySet() It is used to return a collection view of the mappings
contained in this map.
Set keySet() It is used to return a set view of the keys contained in this
map.
V put(Object key, Object value) It is used to insert an entry in the map.
void putAll(Map map) It is used to insert the specified map in the map.
V putIfAbsent(K key, V value) It inserts the specified value with the specified key in the
map only if it is not already specified.
V remove(Object key) It is used to delete an entry for the specified key.
boolean remove(Object key, Object It removes the specified values with the associated
value) specified keys from the map.
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified key and
K,? super V,? extends V> its current mapped value (or null if there is no current
remappingFunction) mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given mapping
super K,? extends V> function, if the specified key is not already associated with
mappingFunction) a value (or is mapped to null), and enters it into this map
unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? super V,? current mapped value if the value for the specified key is
extends V> remappingFunction) present and non-null.
boolean containsValue(Object value) This method returns true if some value equal to the value
exists within the map, else return false.
boolean containsKey(Object key) This method returns true if some key equal to the key
exists within the map, else return false.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map
super V> action) until all entries have been processed or the action throws
an exception.
V get(Object key) This method returns the object that contains the value
associated with the key.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped,
defaultValue) or defaultValue if the map contains no mapping for the
key.
boolean isEmpty() This method returns true if the map is empty; returns
false if it contains at least one key.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a value
super V,? super V,? extends V> or is associated with null, associates it with the given non-
remappingFunction) null value.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified
newValue) key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking
super V,? extends V> function) the given function on that entry until all entries have been
processed or the function throws an exception.
Collection<V> values() It returns a collection view of the values contained in the
map.
int size() This method returns the number of entries in the map.

Java HashMap Example

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.

LinkedHashMap class declaration

Let's see the declaration for java.util.LinkedHashMap class.

1. public class LinkedHashMap<K,V> extends HashMap<K,V> implements Map<K,V>

LinkedHashMap class Parameters

Let's see the Parameters for java.util.LinkedHashMap class.


o K: It is the type of keys maintained by this map.
o V: It is the type of mapped values.

Constructors of Java LinkedHashMap class

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)

Methods of Java LinkedHashMap class


Method Description
V get(Object key) It returns the value to which the specified key is mapped.
void clear() It removes all the key-value pairs from a map.
boolean containsValue(Object value) It returns true if the map maps one or more keys to the specified
value.
Set<Map.Entry<K,V>> entrySet() It returns a Set view of the mappings contained in the map.
void forEach(BiConsumer<? super K,? super V> It performs the given action for each entry in the map until all ent
action) have been processed or the action throws an exception.
V getOrDefault(Object key, V defaultValue) It returns the value to which the specified key is mapped or
defaultValue if this map contains no mapping for the key.
Set<K> keySet() It returns a Set view of the keys contained in the map
protected boolean It returns true on removing its eldest entry.
removeEldestEntry(Map.Entry<K,V> eldest)
void replaceAll(BiFunction<? super K,? super V,? It replaces each entry's value with the result of invoking the given
extends V> function) function on that entry until all entries have been processed or the
function throws an exception.
Collection<V> values() It returns a Collection view of the values contained in this map.
Java LinkedHashMap Example
import java.util.*;
class LinkedHashMap1{
public static void main(String args[]){

LinkedHashMap<Integer,String> hm=new LinkedHashMap<Integer,String>();

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.

Hashtable class declaration

Let's see the declaration for java.util.Hashtable class.

1. public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable


, Serializable

Hashtable class Parameters

Let's see the Parameters for java.util.Hashtable class.

o K: It is the type of keys maintained by this map.


o V: It is the type of mapped values.
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 having the specified initial
loadFactor) capacity and loadFactor.
Hashtable(Map<? extends K,? It creates a new hash table with the same mappings as the given
extends V> t) Map.

Methods of Java Hashtable class


Method Description
void clear() It is used to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
V compute(K key, BiFunction<? super It is used to compute a mapping for the specified key and
K,? super V,? extends V> its current mapped value (or null if there is no current
remappingFunction) mapping).
V computeIfAbsent(K key, Function<? It is used to compute its value using the given mapping
super K,? extends V> function, if the specified key is not already associated with
mappingFunction) a value (or is mapped to null), and enters it into this map
unless null.
V computeIfPresent(K key, It is used to compute a new mapping given the key and its
BiFunction<? super K,? super V,? current mapped value if the value for the specified key is
extends V> remappingFunction) present and non-null.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the
map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
void forEach(BiConsumer<? super K,? It performs the given action for each entry in the map
super V> action) until all entries have been processed or the action throws
an exception.
V getOrDefault(Object key, V It returns the value to which the specified key is mapped,
defaultValue) or defaultValue if the map contains no mapping for the
key.
int hashCode() It returns the hash code value for the Map
Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.
Set<K> keySet() It returns a Set view of the keys contained in the map.
V merge(K key, V value, BiFunction<? If the specified key is not already associated with a value
super V,? super V,? extends V> or is associated with null, associates it with the given non-
remappingFunction) null value.
V put(K key, V value) It inserts the specified value with the specified key in the
hash table.
void putAll(Map<? extends K,? It is used to copy all the key-value pair from map to
extends V> t)) 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 associated
value) specified keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, V It replaces the old value with the new value for a specified
newValue) key.
void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking
super V,? extends V> function) the given function on that entry until all entries have been
processed or the function throws an exception.
String toString() It returns a string representation of the Hashtable object.
Collection values() It returns a collection view of the values contained in the
map.
boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key
exists within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty;
returns false if it contains at least one key.
protected void rehash() It is used to increase the size of the hash table and
rehashes all of its keys.
V get(Object key) This method returns the object that contains the value
associated with the key.
V remove(Object key) It is used to remove the key and its value. This method
returns the value associated with the key.
int size() This method returns the number of entries in the hash
table.

Java Hashtable Example


import java.util.*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

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 )

The Array sorted in ascending order will be given as;

A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 }

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

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.

compareTo(Object obj) method

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.

We can sort the elements of:

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.

Method of Collections class for sorting List elements

public void sort(List list): It is used to sort the elements of List. List elements must be of the
Comparable type

Java Comparable Example

Let's see the example of the Comparable interface that sorts the list elements on the basis of
age.
File: Student.java

class Student implements Comparable<Student>{


int rollno;
String name;
int age;
Student(int rollno,String name,int age){
this.rollno=rollno;
this.name=name;
this.age=age;
}

public int compareTo(Student st){


if(age==st.age)
return 0;
else if(age>st.age)
return 1;
else
return -1;
}
}

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.

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

The commonly used methods of Properties class are given below.

Method Description

public void load(Reader r) It loads data from the Reader object.

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) It returns value based on the key.

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.

Example of Properties class to get information from the properties file

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");

Properties p=new Properties();


p.load(reader);

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.

Example of Properties class to get all the system properties

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/

You might also like