0% found this document useful (0 votes)
2 views27 pages

OOPJ Module 4

Uploaded by

iamnarendra02
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)
2 views27 pages

OOPJ Module 4

Uploaded by

iamnarendra02
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

Mohan Babu University

Department of Computer Science and Engineering


Department of Computer Science and Engineering
Subject Name: OBJECT ORIENTED PROGRAMMING Subject Code: CS T45
Subject Name: OBJECT ORIENTED PROGRAMMING IN JAVA Subject Code: 22AI104002

Prepared By :
Prepared By :
[Link], HOD
[Link] SELVA RAJ, AP /CSE
/[Link],
AP/CSE

UNIT 4

COLLECTIONS IN JAVA
Before Collections:
There are 4 ways to store values in JVM
1. Using variables : can store only one value
2. Using class object : can store multiple fixed number of values of different types
3. Using array object : can store multiple fixed number of values of same type
4. Using collections : can store multiple objects of same and different types
without size limitation
Collection:
● In general terms a collection is a “group of objects”
● The Collection in Java is a framework that provides a facility to store and
manipulate the group of objects.
● A Collection is a group of individual objects represented as a single unit
● Collection Framework is a set of classes and interfaces that implement
commonly reusable collection data structures.
● It works in the manner of a library.
● The ‘[Link]’ package contains all the classes and interfaces for the
Collection framework.
● It provided methods to perform all type of operations on data such as
searching, sorting, insertion, manipulation, and deletion.
● Java Collection framework provides many interfaces such as Set, List, etc.
and classes such as ArrayList, etc.

John Selva Raj


Mohan Babu University

Map

Hash Table 0

0 0

Hash Table

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.

John Selva Raj


Mohan Babu University

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 [Link] package. It is like the Vector in C++.

The ArrayList in Java can have the duplicate elements also. It implements the List interface so
we can use all the methods of the List interface here. The ArrayList maintains the insertion order
internally.

It inherits the AbstractList class and implements List interface.


The important points about the Java ArrayList class are:
Java ArrayList class can contain duplicate elements.
Java ArrayList class maintains insertion order.
Java ArrayList class is non synchronized.
Java ArrayList allows random access because the array works on an index basis.
In ArrayList, manipulation is a little bit slower than the LinkedList in Java because a lot of shifting
needs to occur if any element is removed from the array list.
We can not create an array list of the primitive types, such as int, float, char, etc. It is required to use
the required wrapper class in such cases.

Syntax :
Arraylist<Datatype> Arraylist_Var = new Arraylist<Datatype>();

Constructors of ArrayList
Constructor Description

ArrayList() It is used to build an empty array list.

ArrayList(Collection<? extends E> It is used to build an array list that is initialized with the elements of the
c) collection c.

ArrayList(int capacity) It is used to build an array list that has the specified initial capacity.

Methods of ArrayList
Method Description

void add(int index, E element) It is used to insert the specified element at the specified position in
a list.

boolean add(E e) It is used to append the specified element at the end of a list.

boolean addAll(Collection<? extends E> It is used to append all of the elements in the specified collection
c) to the end of this list, in the order that they are returned by the
specified collection's iterator.

John Selva Raj


Mohan Babu University

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection,
extends E> c) starting at the specified position of the list.

void clear() It is used to remove all of the elements from this list.

void ensureCapacity(int requiredCapacity) It is used to enhance the capacity of an ArrayList instance.

E get(int index) It is used to fetch the element from the particular position of the
list.

boolean isEmpty() It returns true if the list is empty, otherwise false.

Iterator()

listIterator()

int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

Object[] toArray() It is used to return an array containing all of the elements in this list
in the correct order.

<T> T[] toArray(T[] a) It is used to return an array containing all of the elements in this list
in the correct order.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It returns true if the list contains the specified element.

int indexOf(Object o) It is used to return the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.

E remove(int index) It is used to remove the element present at the specified position in
the list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element.

boolean removeAll(Collection<?> c) It is used to remove all the elements from the list.

boolean removeIf(Predicate<? super E> It is used to remove all the elements from the list that satisfies the
filter) given predicate.

protected void removeRange(int It is used to remove all the elements lies within the given range.
fromIndex, int toIndex)

void replaceAll(UnaryOperator<E> It is used to replace all the elements from the list with the specified
operator) element.

void retainAll(Collection<?> c) It is used to retain all the elements in the list that are present in the
specified collection.

John Selva Raj


Mohan Babu University

E set(int index, E element) It is used to replace the specified element in the list, present at the
specified position.

void sort(Comparator<? super E> c) It is used to sort the elements of the list on the basis of the
specified comparator.

Spliterator<E> spliterator() It is used to create a spliterator over the elements in a list.

List<E> subList(int fromIndex, int It is used to fetch all the elements that lies within the given range.
toIndex)

int size() It is used to return the number of elements present in the list.

void trimToSize() It is used to trim the capacity of this ArrayList instance to be the
list's current size.

Java Non-generic Vs. Generic Collection


Java collection framework was non-generic before JDK 1.5. Since 1.5, it is generic.

Java new generic collection allows you to have only one type of object in a collection. Now it is
type-safe, so typecasting is not required at runtime.

Let's see the old non-generic example of creating a Java collection.

ArrayList list=new ArrayList();//creating old non-generic arraylist


Let's see the new generic example of creating java collection.

ArrayList<String> list=new ArrayList<String>();//creating new generic arraylist


In a generic collection, we specify the type in angular braces. Now ArrayList is forced to have
the only specified type of object in it. If you try to add another type of object, it gives a compile-time
error.

import [Link].*;
public class ArrayListExample1{
public static void main(String args[]){ Output: Mango
Apple
ArrayList<String> list=new ArrayList<String>();//Creating arraylist Banana
[Link]("Mango");//Adding object in arraylist Grapes
[Link]("Apple");
[Link]("Banana");
[Link]("Grapes");
//Printing the arraylist object
[Link](list);
}
}

John Selva Raj


Mohan Babu University

Java LinkedList class

Java LinkedList class uses a doubly linked list to store the elements. It provides a linked-list data
structure. It inherits the AbstractList class and implements List and Deque interfaces.

The important points about Java LinkedList are:

o Java LinkedList class can contain duplicate elements.


o Java LinkedList class maintains insertion order.
o Java LinkedList class is non synchronized.
o In Java LinkedList class, manipulation is fast because no shifting needs to occur.
o Java LinkedList class can be used as a list, stack or queue.

Syntax:

Linkedlist<Datatype> Linkedlist_Var = new Linkedlist<Datatype>();

Constructors of Java LinkedList


Constructor Description

LinkedList() It is used to construct an empty list.

LinkedList(Collection<? It is used to construct a list containing the elements of the specified collection,
extends E> c) in the order, they are returned by the collection's iterator.

Methods of Java LinkedList


Method Description

boolean add(E e) It is used to append the specified element to the end of a list.

void add(int index, E element) It is used to insert the specified element at the specified position index
in a list.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to
E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.

boolean addAll(Collection<? extends It is used to append all of the elements in the specified collection to
E> c) the end of this list, in the order that they are returned by the specified
collection's iterator.

boolean addAll(int index, Collection<? It is used to append all the elements in the specified collection, starting
John Selva Raj
Mohan Babu University

extends E> c) at the specified position of the list.

void addFirst(E e) It is used to insert the given element at the beginning of a list.

void addLast(E e) It is used to append the given element to the end of a list.

void clear() It is used to remove all the elements from a list.

Object clone() It is used to return a shallow copy of an ArrayList.

boolean contains(Object o) It is used to return true if a list contains a specified element.

Iterator<E> descendingIterator() It is used to return an iterator over the elements in a deque in reverse
sequential order.

E element() It is used to retrieve the first element of a list.

E get(int index) It is used to return the element at the specified position in a list.

E getFirst() It is used to return the first element in a list.

E getLast() It is used to return the last element in a list.

int indexOf(Object o) It is used to return the index in a list of the first occurrence of the
specified element, or -1 if the list does not contain any element.

int lastIndexOf(Object o) It is used to return the index in a list of the last occurrence of the
specified element, or -1 if the list does not contain any element.

ListIterator<E> listIterator(int index) It is used to return a list-iterator of the elements in proper sequence,
starting at the specified position in the list.

boolean offer(E e) It adds the specified element as the last element of a list.

boolean offerFirst(E e) It inserts the specified element at the front of a list.

boolean offerLast(E e) It inserts the specified element at the end of a list.

E peek() It retrieves the first element of a list

E peekFirst() It retrieves the first element of a list or returns null if a list is empty.

E peekLast() It retrieves the last element of a list or returns null if a list is empty.

E poll() It retrieves and removes the first element of a list.

E pollFirst() It retrieves and removes the first element of a list, or returns null if a
list is empty.

E pollLast() It retrieves and removes the last element of a list, or returns null if a list
is empty.
John Selva Raj
Mohan Babu University

E pop() It pops an element from the stack represented by a list.

void push(E e) It pushes an element onto the stack represented by a list.

E remove() It is used to retrieve and removes the first element of a list.

E remove(int index) It is used to remove the element at the specified position in a list.

boolean remove(Object o) It is used to remove the first occurrence of the specified element in a
list.

E removeFirst() It removes and returns the first element from a list.

boolean It is used to remove the first occurrence of the specified element in a


removeFirstOccurrence(Object o) list (when traversing the list from head to tail).

E removeLast() It removes and returns the last element from a list.

boolean It removes the last occurrence of the specified element in a list (when
removeLastOccurrence(Object o) traversing the list from head to tail).

E set(int index, E element) It replaces the element at the specified position in a list with the
specified element.

Object[] toArray() It is used to return an array containing all the elements in a list in
proper sequence (from first to the last element).

<T> T[] toArray(T[] a) It returns an array containing all the elements in the proper sequence
(from first to the last element); the runtime type of the returned array
is that of the specified array.

int size() It is used to return the number of elements in a list.

Example: import [Link].*;


public class LinkedList1{
public static void main(String args[]){

LinkedList<String> al=new LinkedList<String>(); Output: Ravi


[Link]("Ravi"); Vijay
[Link]("Vijay"); Ravi
Ajay
[Link]("Ravi");
[Link]("Ajay");

Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
John Selva Raj
Mohan Babu University

Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can store n-number
of elements in it as there is no size limit. It is a part of Java Collection framework since Java 1.2. It is
found in the [Link] package and implements the List interface, so we can use all the methods of List
interface here.

It is recommended to use the Vector class in the thread-safe implementation only. If you don't need to
use the thread-safe implementation, you should use the ArrayList, the ArrayList will perform better in
such case.

The Iterators returned by the Vector class are fail-fast. In case of concurrent modification, it fails and
throws the ConcurrentModificationException.

Syntax:

Vector<Datatype> Vector_Var = new Vector<Datatype>();

Java Vector Constructors


Vector class supports four types of constructors. These are given below:

SN Constructor Description

1) vector() It constructs an empty vector with the default size as 10.

2) vector(int initialCapacity) It constructs an empty vector with the specified initial capacity and
with its capacity increment equal to zero.

3) vector(int initialCapacity, int It constructs an empty vector with the specified initial capacity and
capacityIncrement) capacity increment.

4) Vector( Collection<? extends E> c) It constructs a vector that contains the elements of a collection c.

Java Vector Methods


The following are the list of Vector class methods:

SN Method Description

1) add() It is used to append the specified element in the given vector.

2) addAll() It is used to append all of the elements in the specified collection to the end of
this Vector.

3) addElement() It is used to append the specified component to the end of this vector. It
John Selva Raj
Mohan Babu University

increases the vector size by one.

4) capacity() It is used to get the current capacity of this vector.

5) clear() It is used to delete all of the elements from this vector.

6) clone() It returns a clone of this vector.

7) contains() It returns true if the vector contains the specified element.

8) containsAll() It returns true if the vector contains all of the elements in the specified collection.

9) copyInto() It is used to copy the components of the vector into the specified array.

10) elementAt() It is used to get the component at the specified index.

11) elements() It returns an enumeration of the components of a vector.

12) ensureCapacity() It is used to increase the capacity of the vector which is in use, if necessary. It
ensures that the vector can hold at least the number of components specified by
the minimum capacity argument.

13) equals() It is used to compare the specified object with the vector for equality.

14) firstElement() It is used to get the first component of the vector.

15) forEach() It is used to perform the given action for each element of the Iterable until all
elements have been processed or the action throws an exception.

16) get() It is used to get an element at the specified position in the vector.

17) hashCode() It is used to get the hash code value of a vector.

18) indexOf() It is used to get the index of the first occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

19) insertElementAt() It is used to insert the specified object as a component in the given vector at the
specified index.

20) isEmpty() It is used to check if this vector has no components.

21) iterator() It is used to get an iterator over the elements in the list in proper sequence.

22) lastElement() It is used to get the last component of the vector.

23) lastIndexOf() It is used to get the index of the last occurrence of the specified element in the
vector. It returns -1 if the vector does not contain the element.

24) listIterator() It is used to get a list iterator over the elements in the list in proper sequence.

25) remove() It is used to remove the specified element from the vector. If the vector does not
John Selva Raj
Mohan Babu University

contain the element, it is unchanged.

26) removeAll() It is used to delete all the elements from the vector that are present in the
specified collection.

27) removeAllElements() It is used to remove all elements from the vector and set the size of the vector to
zero.

28) removeElement() It is used to remove the first (lowest-indexed) occurrence of the argument from
the vector.

29) removeElementAt() It is used to delete the component at the specified index.

30) removeIf() It is used to remove all of the elements of the collection that satisfy the given
predicate.

31) removeRange() It is used to delete all of the elements from the vector whose index is between
fromIndex, inclusive and toIndex, exclusive.

32) replaceAll() It is used to replace each element of the list with the result of applying the
operator to that element.

33) retainAll() It is used to retain only that element in the vector which is contained in the
specified collection.

34) set() It is used to replace the element at the specified position in the vector with the
specified element.

35) setElementAt() It is used to set the component at the specified index of the vector to the
specified object.

36) setSize() It is used to set the size of the given vector.

37) size() It is used to get the number of components in the given vector.

38) sort() It is used to sort the list according to the order induced by the specified
Comparator.

39) spliterator() It is used to create a late-binding and fail-fast Spliterator over the elements in the
list.

40) subList() It is used to get a view of the portion of the list between fromIndex, inclusive, and
toIndex, exclusive.

41) toArray() It is used to get an array containing all of the elements in this vector in correct
order.

42) toString() It is used to get a string representation of the vector.

43) trimToSize() It is used to trim the capacity of the vector to the vector's current size.

John Selva Raj


Mohan Babu University

Java Vector Example :

import [Link].*;

public class VectorExample {

public static void main(String args[]) {

//Create a vector

Vector<String> vec = new Vector<String>();

//Adding elements using add() method of List

[Link]("Tiger");

[Link]("Lion");

[Link]("Dog");

[Link]("Elephant");

//Adding elements using addElement() method of Vector

[Link]("Rat");

[Link]("Cat");

[Link]("Deer");

[Link]("Elements are: "+vec);

Output:

Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]

John Selva Raj


Mohan Babu University

Java HashSet

Java HashSet class is used to create a collection that uses a hash table for storage. It inherits the
AbstractSet class and implements Set interface.

The important points about Java HashSet class are:

o HashSet stores the elements by using a mechanism called hashing.


o HashSet contains unique elements only.
o HashSet allows null value.
o HashSet class is non synchronized.
o HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
o HashSet is the best approach for search operations.
o The initial default capacity of HashSet is 16, and the load factor is 0.75.

Syntax:

HashSet<Datatype> HashSet_Var = new HashSet<Datatype>();

Difference between List and Set

A list can contain duplicate elements whereas Set contains unique elements only.

Constructors of Java HashSet class


SN Constructor Description

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 It is used to initialize the capacity of the hash set to the given integer
loadFactor) value capacity and the specified load factor.

4) HashSet(Collection<? It is used to initialize the hash set by using the elements of the collection
extends E> c) c.

Methods of Java HashSet class


Various methods of Java HashSet class are as follows:

John Selva Raj


Mohan Babu University

SN Modifier & Method Description


Type

1) boolean add(E e) It is used to add the specified element to this set if it is not
already present.

2) void clear() It is used to remove all of the elements from the set.

3) object clone() It is used to return a shallow copy of this HashSet instance: the
elements themselves are not cloned.

4) boolean contains(Object It is used to return true if this set contains the specified element.
o)

5) boolean isEmpty() It is used to return true if this set contains no elements.

6) Iterator<E> iterator() It is used to return an iterator over the elements in this set.

7) boolean remove(Object It is used to remove the specified element from this set if it is
o) present.

8) int size() It is used to return the number of elements in the set.

9) Spliterator<E> spliterator() It is used to create a late-binding and fail-fast Spliterator over


the elements in the set.

Java HashSet Example

Let's see a simple example of HashSet. Notice, the elements iterate in an unordered collection.

import [Link].*;
class HashSet1{
public static void main(String args[]){
//Creating HashSet and adding elements
HashSet<String> set=new HashSet();
[Link]("One");
[Link]("Two");
[Link]("Three");
[Link]("Four");
[Link]("Five");
Iterator<String> i=[Link](); Output: Five
while([Link]()) One
Four
{ Two
[Link]([Link]()); Three
}
}
}
John Selva Raj
Mohan Babu University

Java TreeSet class

Java TreeSet class implements the Set interface that uses a tree for storage. It inherits AbstractSet class
and implements the NavigableSet interface. The objects of the TreeSet class are stored in ascending
order.

The important points about the Java TreeSet class are:

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quiet fast.
o Java TreeSet class doesn't allow null element.
o Java TreeSet class is non synchronized.
o Java TreeSet class maintains ascending order.

o Java TreeSet class contains unique elements only like HashSet.


o Java TreeSet class access and retrieval times are quite fast.
o Java TreeSet class doesn't allow null elements.
o Java TreeSet class is non-synchronized.
o Java TreeSet class maintains ascending order.
o The TreeSet can only allow those generic types that are comparable. For example The Comparable
interface is being implemented by the StringBuffer class.

Internal Working of The TreeSet Class


TreeSet is being implemented using a binary search tree, which is self-balancing just like a Red-Black
Tree. Therefore, operations such as a search, remove, and add consume O(log(N)) time. The reason
behind this is there in the self-balancing tree. It is there to ensure that the tree height never exceeds
O(log(N)) for all of the mentioned operations. Therefore, it is one of the efficient data structures in order
to keep the large data that is sorted and also to do operations on it.

Syntax:

TreeSet<Datatype> TreeSet_Var = new TreeSet<Datatype>();

Constructors of Java TreeSet Class


Constructor Description

TreeSet() It is used to construct an empty tree set that will be sorted in ascending order
according to the natural order of the tree set.

John Selva Raj


Mohan Babu University

TreeSet(Collection<? extends It is used to build a new tree set that contains the elements of the collection c.
E> c)

Methods of Java TreeSet Class


Method Description

boolean add(E e) It is used to add the specified element to this set if it is


not already present.

boolean addAll(Collection<? extends E> c) It is used to add all of the elements in the specified
collection to this set.

E ceiling(E e) It returns the equal or closest greatest element of the


specified element from the set, or null there is no such
element.

Comparator<? super E> comparator() It returns a comparator that arranges elements in


order.

Iterator descendingIterator() It is used to iterate the elements in descending order.

NavigableSet descendingSet() It returns the elements in reverse order.

E floor(E e) It returns the equal or closest least element of the


specified element from the set, or null there is no such
element.

SortedSet headSet(E toElement) It returns the group of elements that are less than the
specified element.

NavigableSet headSet(E toElement, boolean inclusive) It returns the group of elements that are less than or
equal to(if, inclusive is true) the specified element.

E higher(E e) It returns the closest greatest element of the specified


element from the set, or null there is no such element.

Iterator iterator() It is used to iterate the elements in ascending order.

E lower(E e) It returns the closest least element of the specified


element from the set, or null there is no such element.

E pollFirst() It is used to retrieve and remove the lowest(first)


element.

E pollLast() It is used to retrieve and remove the highest(last)


element.

Spliterator spliterator() It is used to create a late-binding and fail-fast


spliterator over the elements.

John Selva Raj


Mohan Babu University

NavigableSet subSet(E fromElement, boolean It returns a set of elements that lie between the given
fromInclusive, E toElement, boolean toInclusive) range.

SortedSet subSet(E fromElement, E toElement)) It returns a set of elements that lie between the given
range which includes fromElement and excludes
toElement.

SortedSet tailSet(E fromElement) It returns a set of elements that are greater than or
equal to the specified element.

NavigableSet tailSet(E fromElement, boolean inclusive) It returns a set of elements that are greater than or
equal to (if, inclusive is true) the specified element.

boolean contains(Object o) It returns true if this set contains the specified element.

boolean isEmpty() It returns true if this set contains no elements.

boolean remove(Object o) It is used to remove the specified element from this set
if it is present.

void clear() It is used to remove all of the elements from this set.

Object clone() It returns a shallow copy of this TreeSet instance.

E first() It returns the first (lowest) element currently in this


sorted set.

E last() It returns the last (highest) element currently in this


sorted set.

int size() It returns the number of elements in this set.

Example: import [Link].*;


class TreeSet1{
public static void main(String args[]){
//Creating and adding elements Output: Ajay
TreeSet<String> al=new TreeSet<String>(); Ravi
[Link]("Ravi"); Vijay
[Link]("Vijay");
[Link]("Ravi");
[Link]("Ajay");
//Traversing elements
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
} }

John Selva Raj


Mohan Babu University

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 [Link] package.

HashMap in Java is like the legacy Hashtable class, but it is not synchronized. It allows us to store the
null elements as well, but there should be only one null key. Since Java 5, it is denoted
as HashMap<K,V>, where K stands for key and V for value. It inherits the AbstractMap class and
implements the Map interface.

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.

Syntax:

Hashmap<Key Datatype, Value Datatype> Hashmap_Var = new Hashmap<Key Datatype, Value Datatype>();

HashMap class Parameters


Let's see the Parameters for [Link] 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 given
extends V> m) Map object m.

HashMap(int capacity) It is used to initializes the capacity of the hash map to the given integer
value, capacity.

John Selva Raj


Mohan Babu University

HashMap(int capacity, float It is used to initialize both the capacity and load factor of the hash map
loadFactor) 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 value) It removes the specified values with the associated specified keys
from the map.

V compute(K key, BiFunction<? super K,? It is used to compute a mapping for the specified key and its
super V,? extends V> remappingFunction) current mapped value (or null if there is no current mapping).

V computeIfAbsent(K key, Function<? super It is used to compute its value using the given mapping function,
K,? extends V> mappingFunction) if the specified key is not already associated with a value (or is
mapped to null), and enters it into this map unless null.

V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and its
super K,? super V,? extends V> current mapped value if the value for the specified key is present
remappingFunction) 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.

John Selva Raj


Mohan Babu University

void forEach(BiConsumer<? super K,? super It performs the given action for each entry in the map until all
V> action) 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 defaultValue) It returns the value to which the specified key is mapped, 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<? super If the specified key is not already associated with a value or is
V,? super V,? extends V> associated with null, associates it with the given non-null value.
remappingFunction)

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 key.
newValue)

void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking the given
super V,? 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 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 [Link].*;
public class HashMapExample1{
public static void main(String args[]){
HashMap<Integer,String> map=new HashMap<Integer,String>();//Creating HashMap
[Link](1,"Mango"); //Put elements in Map
[Link](2,"Apple");
[Link](3,"Banana"); Output:
Iterating Hashmap...
[Link](4,"Grapes");
1 Mango
2 Apple
[Link]("Iterating Hashmap..."); 3 Banana
for([Link] m : [Link]()){ 4 Grapes
[Link]([Link]()+" "+[Link]());
}
} }
John Selva Raj
Mohan Babu University

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.

Syntax:

Hashtable<Key Datatype, Value Datatype> Hashtable_Var = new Hashtable<Key Datatype, Value Datatype>();

Hashtable class Parameters


Let's see the Parameters for [Link] 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 It accepts an integer parameter and creates a hash table that contains a specified initial
capacity) capacity.

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 K,? It is used to compute a mapping for the specified key and its
John Selva Raj
Mohan Babu University

super V,? extends V> remappingFunction) current mapped value (or null if there is no current mapping).

V computeIfAbsent(K key, Function<? super It is used to compute its value using the given mapping function,
K,? extends V> mappingFunction) if the specified key is not already associated with a value (or is
mapped to null), and enters it into this map unless null.

V computeIfPresent(K key, BiFunction<? It is used to compute a new mapping given the key and its
super K,? super V,? extends V> current mapped value if the value for the specified key is present
remappingFunction) and non-null.

Enumeration elements() It returns an enumeration of the values in the hash table.

Set<[Link]<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,? super It performs the given action for each entry in the map until all
V> action) entries 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 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<? super If the specified key is not already associated with a value or is
V,? super V,? extends V> associated with null, associates it with the given non-null value.
remappingFunction)

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 V> It is used to copy all the key-value pair from map to hashtable.
t))

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 value) It removes the specified values with the associated 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 key.
newValue)

John Selva Raj


Mohan Babu University

void replaceAll(BiFunction<? super K,? It replaces each entry's value with the result of invoking the given
super V,? extends V> function) 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 [Link].*;
class Hashtable1{
public static void main(String args[]){
Hashtable<Integer,String> hm=new Hashtable<Integer,String>();

Output:
[Link](100,"Amit"); 103 Rahul
102 Ravi
[Link](102,"Ravi"); 101 Vijay
[Link](101,"Vijay"); 100 Amit
[Link](103,"Rahul");

for([Link] m:[Link]()){
[Link]([Link]()+" "+[Link]());
}
} }
John Selva Raj
Mohan Babu University

Iterator in Java
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced in order to
iterate over a collection of Java object components entirety one by one. It is free to use in the Java
programming language since the Java 1.2 Collection framework. It belongs to [Link] package.

Though Java Iterator was introduced in Java 1.2, however, it is still not the oldest tool available to
traverse through the elements of the Collection object. The oldest Iterator in the Java programming
language is the Enumerator predated Iterator. Java Iterator interface succeeds the enumerator iterator
that was practiced in the beginning to traverse over some accessible collections like the ArrayLists.

The Java Iterator is also known as the universal cursor of Java as it is appropriate for all the classes of
the Collection framework. The Java Iterator also helps in the operations like READ and REMOVE. When
we compare the Java Iterator interface with the enumeration iterator interface, we can say that the
names of the methods available in Java Iterator are more precise and straightforward to use.

Advantages of Java Iterator


Iterator in Java became very prevalent due to its numerous advantages. The advantages of Java Iterator
are given as follows -

o The user can apply these iterators to any of the classes of the Collection framework.
o In Java Iterator, we can use both of the read and remove operations.
o If a user is working with a for loop, they cannot modernize(add/remove) the Collection, whereas, if they
use the Java Iterator, they can simply update the Collection.
o The Java Iterator is considered the Universal Cursor for the Collection API.
o The method names in the Java Iterator are very easy and are very simple to use.

Disadvantages of Java Iterator


Despite the numerous advantages, the Java Iterator has various disadvantages also. The disadvantages
of the Java Iterator are given below -

o The Java Iterator only preserves the iteration in the forward direction. In simple words, the Java Iterator is a
uni-directional Iterator.
o The replacement and extension of a new component are not approved by the Java Iterator.
o In CRUD Operations, the Java Iterator does not hold the various operations like CREATE and UPDATE.
o In comparison with the Spliterator, Java Iterator does not support traversing elements in the parallel
pattern which implies that Java Iterator supports only Sequential iteration.

John Selva Raj


Mohan Babu University

o In comparison with the Spliterator, Java Iterator does not support more reliable execution to traverse the
bulk volume of data.

How to use Java Iterator?


When a user needs to use the Java Iterator, then it's compulsory for them to make an instance of the
Iterator interface from the collection of objects they desire to traverse over. After that, the received
Iterator maintains the trail of the components in the underlying collection to make sure that the user will
traverse over each of the elements of the collection of objects.

If the user modifies the underlying collection while traversing over an Iterator leading to that collection,
then the Iterator will typically acknowledge it and will throw an exception in the next time when the user
will attempt to get the next component from the Iterator.

Java Iterator Methods


The following figure perfectly displays the class diagram of the Java Iterator interface. It contains a total
of four methods that are:

o hasNext()
o next()
o remove()
o forEachRemaining()

The forEachRemaining() method was added in the Java 8. Let's discuss each method in detail.

o boolean hasNext(): The method does not accept any parameter. It returns true if there are more elements
left in the iteration. If there are no more elements left, then it will return false.
If there are no more elements left in the iteration, then there is no need to call the next() method. In
simple words, we can say that the method is used to determine whether the next() method is to be called
or not.
o E next(): It is similar to hasNext() method. It also does not accept any parameter. It returns E, i.e., the next
element in the traversal. If the iteration or collection of objects has no more elements left to iterate, then it
throws the NoSuchElementException.
o default void remove(): This method also does not require any parameters. There is no return type of this
method. The main function of this method is to remove the last element returned by the iterator
traversing through the underlying collection. The remove () method can be requested hardly once per the
next () method call. If the iterator does not support the remove operation, then it throws the
UnSupportedOperationException. It also throws the IllegalStateException if the next method is not yet
called.

John Selva Raj


Mohan Babu University

o default void forEachRemaining(Consumer action): It is the only method of Java Iterator that takes a
parameter. It accepts action as a parameter. Action is nothing but that is to be performed. There is no
return type of the method. This method performs the particularized operation on all of the left
components of the collection until all the components are consumed or the action throws an exception.
Exceptions thrown by action are delivered to the caller. If the action is null, then it throws a
NullPointerException.

Example of Java Iterator


Now it's time to execute a Java program to illustrate the advantage of the Java Iterator interface. The below code
produces an ArrayList of city names. Then we initialize an iterator applying the iterator () method of the ArrayList.
After that, the list is traversed to represent each element.

[Link]
import [Link].*;
import [Link].*;

public class JavaIteratorExample {


public static void main(String[] args)
{
ArrayList<String> cityNames = new ArrayList<String>();

[Link]("Delhi");
[Link]("Mumbai");
[Link]("Kolkata");
[Link]("Chandigarh");
[Link]("Noida");

// Iterator to iterate the cityNames


Iterator iterator = [Link]();

[Link]("CityNames elements : ");

while ([Link]())
[Link]([Link]() + " ");

[Link]();
}
}
John Selva Raj
Mohan Babu University

Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida

Points to Remember
o The Java Iterator is an interface added in the Java Programming language in the Java 1.2 Collection
framework. It belongs to [Link] package.
o It is one of the Java Cursors that are practiced to traverse the objects of the collection framework.
o The Java Iterator is used to iterate the components of the collection object one by one.
o The Java Iterator is also known as the Universal cursor of Java as it is appropriate for all the classes of the
Collection framework.
o The Java Iterator also supports the operations like READ and REMOVE.
o The methods names of the Iterator class are very simple and easy to use compared to the method names
of Enumeration Iterator.

John Selva Raj

You might also like