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

Module v Java

The document provides an overview of the Java Collections Framework, detailing its importance for Java development and its evolution since Java 1.2. It explains the concept of collections as groups of objects, the types of objects that can be stored, and the limitations of traditional data storage methods like variables and arrays. Additionally, it describes various collection interfaces and classes, including List, Set, Queue, and Map, and their respective functionalities.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Module v Java

The document provides an overview of the Java Collections Framework, detailing its importance for Java development and its evolution since Java 1.2. It explains the concept of collections as groups of objects, the types of objects that can be stored, and the limitations of traditional data storage methods like variables and arrays. Additionally, it describes various collection interfaces and classes, including List, Set, Queue, and Map, and their respective functionalities.

Uploaded by

Shashank S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 212

Module - V

Collection Framework

Prepared by Ms. J Karthiyayini J


Collections Overview
• Collections framework in Java is one of the most valuable and
interesting topics of Java language. How important it is?
• Without using collection concepts, you cannot develop any
production level software application in Java. Therefore, every Java
learner has to learn the collections framework.
• Initially, collection framework is simply called Java.util package
or Collection API. Later on, Sun Microsystem had introduced the
collection framework in Java 1.2. It was developed and designed by
“Joshua Bloch”.
• Later on, after Java 1.2, it is known as collections framework. From
Java 1.5 onwards, The Sun Microsystem added some more new
concepts called Generics.
• Due to adding Generics concepts, a lot of changes happened in the
collections classes. That’s why Java 1.5 onwards, people started
calling it Collections and Generics.
What is Collection in Java

• A collection is a group of objects. In Java, these


objects are called elements of the collection.
• Real-time Examples:
1. In childhood, you had a kiddy bank. In the kiddy
bank, you had collected a lot of coins. This kiddy
bank is called collection and the coins are
nothing but objects.
2. A classroom is a collection of students. So, the
classroom is nothing but a collection and
students are objects.
• Technically, a collection is an object or container which
stores a group of other objects as a single unit or single
entity. Therefore, it is also known as container object or
collection object in java.
• A container object means it contains other objects. In
simple words, a collection is a container that stores
multiple elements together.
• JVM (Java Virtual Machine) stores the reference of other
objects into a collection object. It never stores physical
copies of other objects because other objects are already
available in the memory and storing another copy of
objects into a collection object would be a wasting of
memory.
A collection object has a class that is known as collection class or container class. All
collection classes are present in java.util package. Here, util stands for utility. A
group of collection classes is called collections framework in java.
• A simple example of a collection is given
below:
// Create a container list of cities (objects or elements).
ArrayList<String> cities = new ArrayList<String>();
// Adding names of cities.
cities.add(“New York”);
cities.add(“Dhanbad”);
cities.add(“Mumbai”);
Types of Objects Stored in Collection
(Container) Object
• There are two types of objects that can be stored in a collection or
container object. They are as follows:
1. Homogeneous objects:
• Homo means same. Homogeneous objects are a group of multiple objects
that belong to the same class.
• For example, suppose we have created three objects Student s1, Student
s2, and Student s3 of the same class ‘Student’. Since these three objects
belong to the same class that’s why they are called homogeneous objects.
2. Heterogeneous objects:
• Hetero means different. Heterogeneous objects are a group of different
objects that belong to different classes.
• For example, suppose we have created two different objects of different
classes such as one object Student s1, and another one object Employee e1.
Here, student and employee objects together are called a collection of
heterogeneous objects.
• These objects can also be further divided into two types. They
are as follows:
1. Duplicate objects:
• The multiple objects of a class that contains the same data are
called duplicate objects. For example, suppose we create two
person objects Person p1 and Person p2. Both of these
objects have the same data.
Person p1 = new Person( "abc");
Person p2 = new Person("abc");
• Since the above two objects have the same data “abc”
therefore, these are called duplicate objects.
2. Unique objects:
• The multiple objects of a class that contains different data are
called unique objects. For example:
Person p1 = new Person("abcd");
Person p2 = new Person("abcde");
A unique or duplicate object depends on its internal data.
What is need for Collections in Java?
• First, we understand different ways to store values in Java
application by JVM. There is a total of four ways to store
values in Java application by JVM.
1. Using variable approach:
• Suppose you want to store one value in the memory then you
will create one variable and assign a value like this: int x = 10;
• The purpose of variable x is to store one int value 10. If we
want to store two int values, we will create two variables like
this:
int x = 10; int y = 20;
• Similarly, for three values, the third variable will be required,
and so on.
• There is no problem to store until the third or fourth value.
But if we want to store 5000 values then declaring 5000
variables in a program is the worst kind of programming
practice and it will not be in the readable format.
• Thus, the limitations of using the variable approach are as follows:
• ➲ The limitation of a variable is that it can store only one value at a
time.
➲ The readability and reusability of the code will be down.
➲ JVM will take more time for execution.
• Hence, the problem facing this approach can be overcome by using
the second approach “Class object”.
2. Using class object approach:
• Using a class object, we can store multiple “fixed” number of values
of different types. For example, suppose we have created a class
named Employee and declare two variables inside the class. Look at
the code.
class Employee
{
int eNo;
String eName; }
// Creating an object of Employee class.
Employee e1 = new Employee();
• So can you think how many values can store in this employee
object?
• The answer is only two but if you will want to store the third
value, it will not possible. Therefore, this approach is only
suitable to store a fixed number of different values. To
overcome this problem, we should use the third technique
“Array object”.
3. Using array object approach:
We can store a group of objects into an array. Let’s take an
example to understand it. Suppose we want to store 5000
objects of Student class into an array. For this purpose, we
need to create an array object of Student type like this:
Student[ ] st = new Student[5000];
This array can store 5000 Student objects.
• The biggest advantage of an array is that we can store a huge number of
values by using a single variable st and retrieve them easily.
• Array mechanism helps to improve the readability of the code in java
programming but there are several types of problems and limitations with
the array. They are as follows:
1. We can easily store multiple “fixed” numbers of values of homogeneous
data type i.e. Array can store only similar types of data. Suppose if we
create an Employee type array object.
2. An array is static in nature. It is fixed in length and size. We cannot change
(increase/decrease) the size of the array based on our requirements once
they created.
Hence, to use an array, we must know the size of an array to store a group of
objects in advance, which may not always be possible.
3. We can add elements at the end of an array easily. But, adding and deleting
elements or objects in the middle of array is difficult.
4. We cannot insert elements in some sorting order using array concept
because array does not support any method. We will have to write the
sorting code for this but in the case of collection, ready-made method
support is available for sorting using Tree set.
5. We cannot search a particular element using an array, whether the
particular element is present or not in the array index. For this, we will
have to write the searching code using array but in the case of collection,
one readymade method called contains() method is available.
Due to all these above limitations of array, programmers need a better
mechanism to store a group of objects. So, the alternative option is a
collection object or container object in java.
4. Using collection object:
• By using collection object, we can store the same or different data
without any size limitation. Thus, technically, we can define the
collections as:
A collection in java is a container object that is used for storing
multiple homogeneous and heterogeneous, duplicate, and unique
elements without any size limitation.
What is Collections Framework in
Java?
• A framework in java is a set of several classes and interfaces
which provide a ready-made architecture.
• A Java collections framework is a sophisticated hierarchy of
several predefined interfaces and implementation classes that
can be used to handle a group of objects as a single entity.
• In simple words, a collections framework is a class library to
handle groups of objects. It is present in java.util package. It
allows us to store, retrieve, and update a group of objects.
• Collections framework in Java supports two types of
containers:
1. One for storing a collection of elements (objects), that is
simply called a collection.
2. The other, for storing key/value pairs, which is called a map.
Q.Does a collection object store copies of other
objects?
A: No, a collection object works with reference
types. It stores references of other objects,
not copies of other objects.
Q. Can we store a primitive data type into a
collection?
A: No, collections store only objects.
e➝ extends, I➝ implements
Extends: Extends is a keyword that is used for developing inheritance between two
classes and two interfaces.
Implements: Implements is a keyword used for developing inheritance between class
and interface.
Collection Interfaces
• The Collection interface is the root interface of the Java
collections framework.
• There are two groups of interfaces.
1. Collections
2. Maps
• There is no direct implementation of this interface. However,
it is implemented through its subinterfaces like List, Set,
and Queue.
• For example, the ArrayList class implements the List interface
which is a subinterface of the Collection Interface.
• As mentioned above, the Collection interface includes
subinterfaces that are implemented by various classes in Java.
1.List Interface
The List interface is an ordered collection that allows us to add and remove
elements like an array.

2. Set Interface
The Set interface allows us to store elements in different sets similar to the
set in mathematics. It cannot have duplicate elements.

3. Queue Interface
The Queue interface is used when we want to store and access elements
in First In, First Out(FIFO) manner.
Graphical representation of Collection's interfaces
Graphical representation of Map’s interfaces
Iterable Interface
• In Java ,there is now an iterable interface (java.lang.Iterable).
It is the root interface of the Java collection Classes. The
collection interface extends iterable, so all subtypes of
Collection also implement the iterable interface.
• The Syntax of the Iterable interface is given below
public interface Iterable<T>
• A collection provide an iterator which allows a sequential
access to the element of collection. An iterator can be
obtained by calling the following method of collection
interface:
public Iterator iterator()
(Or)
public interface Iterable<T> {
public Iterator<T> iterator();
}
Methods of Iterator
• public boolean hasNext()
• public Object next()
• public Object remove()
ListIterator Interface
• This is the subinterface of iterator.which allows the programmer to
travel in the list in either direction and make modifications to the
underlying list
Methods of ListIterator
• public boolean hasNext()
• public boolean hasPrevious()
• public Object next()
• public Object previous()
• public Int nextIndex()
• public Int previousIndex()
• public void remove()
• public void add(Object o)
• public void set(Object o)
Collection Interface

• The Collection interface (java.util.Collection) is one of the


root interfaces of the Java collection classes. Though you do
not instantiate a collection directly, but rather a subtype of
collection, you may often treat these subtypes uniformly as
a collection.

• Collection myCollection = new HashSet();

• The Collection interface can be a generic like this:

• Collection <String> myCollection = new HashSet<String>();


Collection Subtypes
• The following interfaces (collection types) extends the
collection interface:
1. List
2. Set
3. SortedSet
4. NavigableSet
5. Queue
6. Deque
A description of these interfaces is given below.
The collection interface is a group of objects, with duplicates
allowed.
• Set extends Collection but forbids duplicates.
• List extends Collection and also allows duplicates and
introduces positional indexing.
• Map extends neither Set nor Collection
Interfaces Description Concrete Classes

A basic interface that defines


the normal operation that
Collection allows a collection of objects
to be maintained or handle as
single elements.

Set (Unique Element no


HashSet
order) A set of unique elements .
LinkedHashSet

SortedSet (Unique element A set in which the elements


TreeSet
but in sorted order) are stored in some order.

Vector
List (Duplicate elements but in A sequence of elements that
ArrayList
insertion order) need not be unique.
LinkedList

A basic interface that defines HashMap


Map (Unique Keys) operation for maintaining LinkedHashMap
mapping of keys to values. HashTable

This interface maintaining


SortedMap (Unique keys but
mapping in sorted in key TreeMap
in sorted order)
order.
Queue

• A Queue is a collection for holding elements prior to


processing. Besides basic Collection operations, queues
provide additional insertion, removal, and inspection
operations.
public interface Queue<E> extends Collection<E>
{
E element();
boolean offer(E e);
E peek();
E poll();
E remove();
}
Deque

• The Deque interface is a subtype of the Queue


interface. It represents a queue where you can
insert and remove elements from both ends of
the queue.
• Thus, "Deque" is short for "Double Ended Queue"
and is pronounced "deck",like a deck of
cards. NavigableSet The NavigableSet interface is
a subtype of the SortedSet interface. It behaves
like a SortedSet with the exception you have
navigation methods available in addition to the
sorting mechanisms of the SortedSet.
Map interfaces
• The Map interface represents a mapping
between a key and a value. the Map interface
is not a subtype of the collection interface.
• Therefore it behaves a bit different from the
rest of the collection types.
• Map interface is not inherited by the
collection interface. It represents an object
that stores and retrieves elements in the form
of a Key/Value pairs and their location within
the Map are determined by a Key.
Map uses a hashing technique for storing key-value pairs.
•It doesn’t allow to store the duplicate keys but duplicate values are allowed.
• HashMap, HashTable, LinkedHashMap, TreeMap classes implements Map
interface.
SortedMap Interface
This interface represents a Map whose elements are stored in their natural
ordering. It extends the Map interface which in turn is implemented by
TreeMap classes.
Methods of Collection

• The Collection interface includes various methods that can be used


to perform different operations on objects. These methods are
available in all its subinterfaces.
1. add() - inserts the specified element to the collection
2. size() - returns the size of the collection
3. remove() - removes the specified element from the collection
4. iterator() - returns an iterator to access elements of the collection
5. addAll() - adds all the elements of a specified collection to the
collection
6. removeAll() - removes all the elements of the specified collection
from the collection
7. clear() - removes all the elements of the collection
Example-1
import java.util.*;
import java.util.Map.Entry;
public class DemoMap {
public static void main(String args[]) {
HashMap dm = new HashMap();
System.out.println(dm.size());
dm.put("1001", "aa");
dm.put("1002", "bb");
dm.put("1003", "cc");
dm.put("1004", "dd");
dm.put("1005", "ee");
Set s = dm.entrySet();
Iterator en = s.iterator();
while (en.hasNext()) {
Map.Entry e = (Map.Entry) en.next();
String k = (String) e.getKey();
String v = (String) e.getValue();
System.out.println(k + "=" + v);
}
System.out.println(dm.size());
}
}
Set Interface
• A set in Java is an unordered collection of unique
elements or objects. In other words, a set is a collection
of elements that are not stored in a particular order.
• Elements are simply added to the set without any control
over where they go. For example, in many applications,
we do not need to care about the order of elements in a
collection.
• A collection of elements is not stored in a particular
order into a set.
• We can add elements in a set and iterate over all
elements in a set. It will grow dynamically when
elements are stored in it. We can also check whether a
particular element is present in the set.
• A set will not allow duplicate elements. That means an
element can exist only once in the set. If we try to add the
same element that is already present in the set, then it is not
stored in the set. That’s why each element in a set is unique.
• Set in Java can be used to remove duplicate elements from
the collection.
• The Set interface extends Collection interface. Set interface
does not have it’s own methods. All it’s methods are inherited
from Collection interface. The only change that has been
made to Set interface is that add() method will return false if
you try to insert an element which is already present in the
set.
Properties Of Set
• Set contains only unique elements. It does not allow duplicates.
• Set can contain only one null element.
• Random access of elements is not possible.
• Order of elements in a set is implementation
dependent. HashSet elements are ordered on hash code of
elements. TreeSet elements are ordered according to supplied
Comparator (If no Comparator is supplied, elements will be placed
in ascending order) and LinkedHashSet maintains insertion order.
• Set interface contains only methods inherited from Collection
interface. It does not have it’s own methods. But, applies restriction
on methods so that duplicate elements are always avoided.
• One more good thing about Set interface is that the stronger
contract between equals() and hashCode() methods. According to
this contract, you can compare two set instances of different
implementation types (HashSet, TreeSet and LinkedHashSet).
• Two set instances, irrespective of their implementation types, are
said to be equal if they contain same elements.
Methods Of Set Interface

Method Description
It is used to add the specified element in
boolean add(Object o)
this set.
This method adds all the elements in the
boolean addAll(Collection c)
given collection.
It is used to get the number of elements in
int size()
the set.
This method checks that the set is empty
boolean isEmpty()
or not.
It is used to remove all the elements from
void clear()
the set.
This method returns true if this set
boolean contains(Object o)
contains the given element.
Method Description
This method returns true if this set
boolean containsAll(Collection c) contains all the elements of the given
collection.
It is used to remove the specified element
boolean remove(Object o)
from this set.
It removes all the elements in the given
boolean removeAll(Collection c)
collection from the set.
It returns an Iterator over the elements in
Iterator iterate()
this set.
It is used to compare the given element
boolean equals(Object o)
for equility in this set.
It is used to get the hashCode value for
int hashCode()
this set.
Example-2
package iterateSet;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class IterateSetEx
{
public static void main(String[] args)
{
// Create a generic set object of type String.
Set<String> s = new HashSet<String>(); // s.size() is 0.
int size = s.size();
System.out.println("Size before adding elements: " +size);
s.add("Orange"); // s.size() is 1.
s.add("Red"); // s.size() is 2.
s.add("Blue"); // s.size() is 3.
s.add("Yellow"); // s.size() is 4.
s.add("Green"); // s.size() is 5.
System.out.println("Elements in set");
System.out.println(s);
s.remove("Blue");
System.out.println("Set elements after removing");
System.out.println(s);
boolean search = s.contains(“Blue”);
System.out.println("Is Element A present in set: " +search);
Iterator<String> itr = s.iterator();
System.out.println("Iteration using Iterator
method");
while(itr.hasNext())
{
Object str = itr.next();
System.out.println(str);
}
}}
When to use Set?

1. If you want to represent a group of individual


elements as a single entity where duplicates
are not allowed and insertion order is not
preserved then we should go for the Set.
2. If your requirement is to get unique elements,
set is the best choice for this.
3. If you want to remove duplicate elements
without maintaining the insertion order from
the non-set collection, you should go for set.
• Note:
• During iteration, we cannot add an element to
a set at an iterator position. If we try to add an
element during iteration, JVM will throw an
exception
named ConcurrentModificationException.
• Key point: Iteration means repeating the same
operation multiple times.
Example-3
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class AddDemo
{
public static void main(String[] args)
{
Set<String> set= new HashSet<>();
set.add("Banana");
set.add("Orange");
set.add("Apple");
set.add("Mango");
Iterator<String> itr = set.iterator(); while(itr.hasNext())
{
Object str = itr.next();
System.out.println(str);
set.add("Grapes"); // Adding element during //iteration.
It will throw //ConcurrentModificationException.
}
}
}
Iterate Set using forEach loop in Java 1.8?
package iterateSet;
Example-4
import java.util.HashSet;
import java.util.Set;
public class IterateSetEx
{
public static void main(String[] args)
{
Set<Character> s = new HashSet<Character>();
s.add('A');
s.add('B');
s.add('C');
s.add('D');
s.add('E');
System.out.println(s);
System.out.println("Iterating using forEach loop in Java 1.8");
s.forEach(System.out::println);
}}
Java HashSet(Class)

• HashSet in Java is an unordered collection of elements


(objects) that contains only unique elements. That is, it allows
duplicate free elements to be stored.
• It internally uses Hashtable data structure to store a set of
unique elements. It is much faster and gives constant-time
performance for searching and retrieving elements.
• HashSet was introduced in Java 1.2 version and it is present in
java.util.HashSet package.
Features of HashSet
• There are several important features of Java HashSet that should be
kept in mind. They are as follows:
1. The underlying data structure of HashSet is Hashtable. A hash table
stores data by using a mechanism called hashing.
2. HashSet does not allow duplicate elements. If we try to add a
duplicate element in HashSet, the older element would be
overwritten.
3. It allows only one null element. If we try to add more than one null
element, it would still return only one null value.
4. HashSet does not maintain any order in which elements are added.
The order of the elements will be unpredictable. It will return in any
random order.
5. It is much faster due to the use of hashing technique and gives
constant-time performance for adding (insertion), retrieval, removal,
contains, and size operations.
Hashing provides constant execution time for methods like add(),
remove(), contains(), and size() even for the large set.
6. HashSet class is not synchronized which means it is not
thread-safe. Therefore, multiple threads can use the same
HashSet object at the same time and will not give the
deterministic final output.
If you want to synchronize HashSet, use
Collections.synchronizeSet() method.
7. The iterator returned by HashSet class is fail-fast which means
any modification that happened in the HashSet during
iteration, will throw ConcurrentModificationException.
Constructors of HashSet class
• The following constructors are defined for Java HashSet
class. They are as follows:
1. HashSet(): It constructs an empty HashSet (i.e, default
HashSet). The default capacity is 16. The syntax to create
Hashset object is as follows:
HashSet hset = new HashSet();
HashSet<T> hset = new HashSet<T>(); // Generic form. T is
//the type of object that HashSet will hold.
2. HashSet(int initialCapacity): It initializes the capacity of
HashSet. When the set capacity reaches full and a new
element is added, the capacity of the hash set is
expended automatically.
• The internal structure will double in size before adding a new
element. The general syntax in generic form is as follows:
HashSet<T> hset = new HashSet<T>(int initialCapacity);
3. HashSet(int initialCapacity, float fillRatio): This form of
constructor initializes capacity and fill ratio (also called load
factor or load capacity) of the hash set.
• When the number of elements is greater than capacity of
HashSet, the size of the HashSet is grown automatically by
multiplying capacity with load factor.
• The default value of the load factor is 0.75. The value of the
fill ratio ranges from 0.0 to1.0.
• The general syntax to create an object of HashSet with initial
capacity and load factor is as follows:
HashSet<T> hset = new HashSet<T>(int initialCapacity, float loadFactor);
• For example: HashSet<Integer> hset = new HashMap<Integer>(30, 0.7f);
4. HashSet(Collection c): It initializes HashSet by using elements
of c. This constructor acts as a copy constructor. It copies
elements from one collection into the newly created
collection. We cannot provide a custom initial capacity or fill
ratio.
• If the original collection had duplicate elements, only one
duplicate element will be allowed in the final created set.
• Note: Constructors that do not take a load factor, 0.75 is used.
HashSet Class Methods in Java
• Java HashSet class does not define any additional methods. It
inherits methods of its parent classes and methods of the
implemented interface.
• The various methods provided by its superclasses and interfaces are
as follows:
1. boolean add(Object o): This method is used to add the specified
element in this set. It returns true if set does not already contain a
specified element.
2. boolean addAll(Collection c): This method is used to add a group of
elements from another collection to the set.
• Each element in the collection will be added to the current set via
calling add() method on each element. It returns true if the current
set changes.
• If no elements are added, false is returned. A
UnsupportedOperationException will be thrown when a current set
does not support adding elements.
3. boolean remove(Object o): This method is used to
remove the specified element from the set.
• To remove an element, set internally use equals()
method for each element. If the element is found,
element is removed from set and returns true.
• If not found, false is returned. If the removal is not
supported, you will get
UnsupportedOperationException.
4. void clear: This method is used to remove all elements
from a set. It returns nothing.
5. boolean contains(Object element): To check a specific
element is present or not in the set, use contains()
method.
• If the specified element is found in the set, it returns
true otherwise false. The equality checking is done
through the element’s equal method.
6. int size(): If you wish to know how many elements are
in a set, call size() method.
7. boolean isEmpty(): If you wish to check whether
HashSet contains elements or not. Call isEmpty()
method.
8. Object clone(): Since HashSet implements cloneable
interface. So, we can create a shallow copy of that hash
set by calling clone() method of HashSet.
9. boolean equals(Object o): The HashSet class defines
equality by using equals() method on each element
within the set.
10. int hashCode(): The HashSet class overrides the
hashCode() method to define an appropriate hash code
value for the set. It returns the same hash code by sum
up all hash codes of all the elements.
Example-5
package hashSetTest;
import java.util.HashSet;
public class HashSetExample1
{
public static void main(String[] args)
{ // Create a HashSet object.
HashSet<String> set = new HashSet<String>();
set.add("First");
set.add("Second");
set.add("Third");
set.add("Fourth");
set.add("Fifth");
// Adding duplicate elements that will be ignored.
set.add("First");
set.add("Third");
// Adding of null elements.
set.add(null);
set.add(null); // Ignored.
System.out.println("Unordered and No Duplicate HashSet
Elements");
System.out.println(set); } }
• Output:
Unordered and No Duplicate HashSet Elements
[null, Second, Third, First, Fourth, Fifth]
When to use HashSet in Java?

• HashSet in Java is used when


1. We don’t want to store duplicate elements.
2. We want to remove duplicate elements from
the list.
3. HashSet is more preferred when add and
remove operations are more as compared to
get operations.
4. We are not working in a multithreading
environment.
LinkedHashSet in Java

• LinkedHashSet in Java is a concrete class that implements set


interface and extends HashSet class with a doubly linked list
implementation.
• It internally uses a linked list to store the elements in the set. It was
added in Java 1.4 version.
• Java LinkedHashSet class is the same as HashSet class, except that it
maintains the ordering of elements in the set in which they are
inserted.
• That is, LinkedHashSet not only uses a hash table for storing
elements but also maintains a double-linked list of the elements in
the order during iteration.
• In simple words, elements in the HashSet are not ordered, but
elements in the LinkedHashSet can be retrieved in the same order
in which they were inserted into the set.
Features of LinkedHashSet

• The important features of Java LinkedHashSet class are as


follows that needs to keep in mind.
1. Java LinkedHashSet class contains unique elements like
HashSet. It does not allow to insert of duplicate elements. If
we try to add a duplicate element, it will fail and the iteration
order of the set is not modified.
2. LinkedHashSet class permits to insert null element.
3. LinkedHashSet class in Java is non-synchronized. That means it
is not thread-safe.
4. LinkedHashSet class preserve the insertion order of elements
5. It is slightly slower than HashSet.
6. Linked hash set is very efficient for insertion and deletion of
elements.
Constructor of LinkedHashSet
We can create LinkedHashSet by using one of its four
constructors. They are as follows:
1. LinkedHashSet( ): This constructor is used to create an empty
LinkedHashSet. It is a default LinkedHashSet. The general
syntax to create LinkedHashSet is as follows:
LinkedHashSet<T> lhset = new LinkedHashSet<T>();
2. LinkedHashSet(Collection c): This constructor is used to
initialize the LinkedHashSet with elements of collection c. The
general syntax is as follow:
LinkedHashSet<T> lhset = new LinkedHashSet<T>(Collection c);
3. LinkedHashSet(int initialCapacity): This constructor is used to
create LinkedHashSet with initializing the capacity of the linked
hash set. It takes an integer value to initialize capacity. The
general syntax to create linked hash set in Java is given below:
LinkedHashSet<T> lhset = new LinkedHashSet<T>(int size);
4. LinkedHashSet(int initialCapacity, float loadFactor): This
constructor is used to create LinkedHashSet with initializing
both the capacity and load factor of the linked hash set.
LinkedHashSet<T> lhset = new LinkedHashSet<T>(int initialCapacity, float
loadFactor)
Note: These constructors work the same as the constructors for
HashSet.
Example-6
import java.util.LinkedHashSet;
class Main
{
public static void main(String[] args)
{ LinkedHashSet<Integer> numbers = new LinkedHashSet<Integer>();
numbers.add(2);
numbers.add(5);
numbers.add(6);
System.out.println("LinkedHashSet: " + numbers);
// Using the remove() method
boolean value1 = numbers.remove(5);
System.out.println("Is 5 removed? " + value1);
boolean value2 = numbers.removeAll(numbers);
System.out.println("Are all elements removed? " + value2);
}}
LinkedHashSet: [2, 5, 6]
Is 5 removed? true
Are all elements removed? True
Which is better to use: HashSet or LinkedHashSet?
• If you do not require to maintain order in which elements are
inserted then use HashSet that is more fast and efficient than
LinkedHashSet.
TreeSet
• A TreeSet in Java is another important implementation of the Set
interface that is similar to the HashSet class, with one added
improvement.
• It sorts elements in ascending order while HashSet does not maintain
any order.
• Java TreeSet implements SortedSet interface. It is a collection for
storing a set of unique elements (objects) according to their natural
ordering.
• It creates a sorted collection that uses a tree structure for the storage of
elements or objects. In simple words, elements are kept in sorted,
ascending order in the tree set.
• For example, a set of books might be kept by height or alphabetically by
title and author.In Java TreeSet, access and retrieval of elements are
quite fast because of using tree structure. Therefore, TreeSet is an
excellent choice for quick and fast access to large amounts of sorted
data.
• The only restriction with using tree set is that we cannot add duplicate
Features of TreeSet class in Java
• There are several important features of TreeSet class in java
that must be kept in mind. They are as:
1. Java TreeSet contains unique elements similar to the
HashSet. It does not allow the addition of a duplicate
element.
2. The access and retrieval times are quite fast.
3. TreeSet does not allow inserting null element.
4. TreeSet class is non-synchronized. That means it is not thread-
safe.
5. TreeSet maintains the ascending order. When we add
elements into the collection in any order, the values are
automatically presented in sorted, ascending order.
6. Java TreeSet internally uses a TreeMap for storing elements.
Constructors of Treeset
• TreeSet has the following constructors. We can create a TreeSet instance
by using one of its four constructors.
1. TreeSet( ): This default constructor creates an empty TreeSet that will be
sorted in ascending order according to the natural order of its elements.
2. TreeSet(Collection c): It creates a tree set and adds the elements from a
collection c according to the natural ordering of its elements. All the
elements added into the new set must implement Comparable interface.
If collection c’s elements do not implement Comparable interface or are not
mutually comparable, this constructor throws ClassCastException.
If collection c contains null reference, this constructor throws
NullPointerException.
3. TreeSet(Comparator comp): This constructor creates an empty tree set
that will be sorted according to the comparator specified by comp.
All elements in the tree set are compared mutually by the specified
comparator. A comparator is an interface that is used to implement the
ordering of data.
4. TreeSet(SortedSet s): This constructor creates a tree set that contains the
elements of sorted set s.
Important TreeSet Methods
• TreeSet class in java provides a variety of methods to perform
different tasks. They are as follows:
1. boolean add(Object o): This method is used to add the
specified element to this set if it is not already present.
2. boolean addAll(Collection c): This method is used to add all
the elements of the specified collection to the set.
3. void clear(): It is used to remove all the elements from the set.
4. boolean isEmpty(): This method is used to check that the set
has elements or not. It returns true if the set contains no
elements otherwise returns false.
5. boolean remove(Object o): This method is used to remove
the specified element from the set if it is present.
6. boolean contains(Object o): It returns true if the set has the
specified element otherwise returns false.
7. int size(): This method is used to get the total number of
elements in the set.
8. Iterator iterator(): The iterator() method is used to iterate the
elements in ascending order.
9. Spliterator spliterator(): The splititerator() method is used to
create a late-binding and fail-fast spliterator over the
elements in the tree set.
10. Object clone(): The clone() method is used to get a shallow
copy of this TreeSet instance.
11. Iterator descendingIterator(): It is used to iterate the
elements in descending order.
Example-7
import java.util.Set;
import java.util.TreeSet;
public class TreeSetEx1
{
public static void main(String[] args)
{ // Create a tree set.
Set<String> ts = new TreeSet<>();
// Check Set is empty or not.
boolean empty = ts.isEmpty();
System.out.println("Is TreeSet empty: " +empty);
// Checking the size of TreeSet before adding elements into it.
int size1 = ts.size();
System.out.println("Size of TreeSet: " +size1);
ts.add("India");
ts.add("USA");
ts.add("Australia");
ts.add("New zealand");
ts.add("Switzerland");
System.out.println("Sorted TreeSet: " +ts);
int size2 = ts.size();
System.out.println("Size of TreeSet after adding elements: " +size2);
// Checking for a specific element in set.
boolean element = ts.contains("USA");
System.out.println("Is USA in TreeSet: " +element);
// Removing element from the tree set.
ts.remove("New zealand");
System.out.println("Sorted tree set: " +ts);
ts.clear();
System.out.println("Elements in tree set: " +ts);
}}
List Interface
• A list in Java is a collection for storing elements in sequential
order. Sequential order means the first element, followed by
the second element, followed by the third element, and so on.
• A good realtime example of a list is a line of train bogies on a
track: To get to the fourth bogie from the first bogie, we have to
go through the second and third bogies in that order.
• Java list is a sub-interface of the collection interface that is
available in java.util package. Sub interface means an interface
that extends another interface is called sub interface. Here, the
list interface extends the collection interface.
• The general declaration of list interface in java is as follows:
public interface List<E> extends Collection<E>
• It is an ordered collection where elements are maintained by
index positions because it uses an index-based structure. In
the list interface, the order is retained in which we add
elements. We will also get the same sequence while retrieving
elements.
• It is used to store a collection of elements where duplicate
elements are allowed.
• List interface in java has four concrete subclasses. They are
ArrayList, LinkedList, Vector, and Stack. These four subclasses
implements the list interface.
Features of List Interface
There are the following features of list in java. They are as
follows:
1. The list allows storing duplicate elements in Java. JVM
differentiates duplicate elements by using ‘index’. Index refers
to the position of a certain object in an array. It always starts
at zero.
For example, assume that there is a list with size 10. Suppose the
first element is ‘a’ at zero index position and the second
element is also ‘a’ which is at 9th position. Thus, there are two
‘a’ elements in the list at positions 0 and 9 respectively.
So, JVM will differentiate between both elements in the list
based on their numeral position of the index. Therefore, the
index is very useful and plays an important role to
differentiate objects.
2. In the list, we can add an element at any position.
3. It maintains insertion order. i.e. List can preserve the insertion
order by using the index.
4. It allows for storing many null elements.
5. Java list uses a resizable array for its implementation.
Resizable means we can increase or decrease the size of the
array.
6. Except for LinkedList, ArrayList and Vector is an indexed-based
structure.
7. It provides a special Iterator called a ListIterator that allows
accessing the elements in the forward direction using
hasNext() and next() methods.
In the reverse direction, it accesses elements using hasPrevious()
and previous() methods. We can add, remove elements of the
collection, and can also replace the existing elements with the
new element using ListIterator.
How to create a List in Java?

• To create a list in java, we can use one of its two concrete


subclasses: ArrayList, and LinkedList. We will use ArrayList to
create a list and test methods provided by list interface in the
program section.
List p = new ArrayList();
List q = new LinkedList();
List r = new Vector();
List s = new Stack();
How to create Generic List Object in Java
• After the introduction of Generic in Java 1.5, we can restrict the type of
object that can be stored in the list. The general syntax for creating a list of
objects with a generic type parameter is as follows:
1. List<data type> list = new ArrayList<data type>(); // General sysntax.
For example:
a. List<String> list = new ArrayList<String>(); // Creating a list of objects of
String type using ArrayList.
b. List<Integer> list = new LinkedList<Integer>(); Creating a list of objects of
Integer type using LinkedList.
c. List<String> list1 = new LinkedList<String>();
d. List<obj> list = new ArrayList<obj>(); // obj is the type of object.

For example: List<Book> list=new ArrayList<Book>(); // Book is the type of


object.

2. Starting from Java 1.7, we can use a diamond operator.


a. List<String> str = new ArrayList<>();
b. List<Integer> list = new LinkedList<>();
ArrayList
• ArrayList in Java is a resizable array that can grow or shrink
in the memory whenever needed. It is dynamically created
with an initial capacity.
• It means that if the initial capacity of the array is exceeded,
a new array with larger capacity is created automatically
and all the elements from the current array are copied to
the new array.
• Elements in ArrayList are placed according to the zero-
based index. That is the first element will be placed at 0
index and the last element at index (n-1) where n is the size
of ArrayList.
• Java ArrayList uses a dynamic array internally for storing the
group of elements or data.
• The capacity of ArrayList does not shrink automatically.
When elements are removed from the list, the size of array
list can be shrunk automatically but not capacity.
Features of ArrayList in Java

• There are several features of ArrayList class in Java. They are as


follows:
1. Resizable-array: ArrayList is a resizable array or growable array that
means the size of ArrayList can increase or decrease in size at
runtime. Once ArrayList is created, we can add any number of
elements.
2. Index-based structure: It uses an index-based structure in java.
3. Duplicate elements: Duplicate elements are allowed in the array list.
4. Null elements: Any number of null elements can be added to
ArrayList.
5. Insertion order: It maintains the insertion order in Java. That is
insertion order is preserved.
6. Heterogeneous objects: Heterogeneous objects are allowed
everywhere except TreeSet and TreeMap. Heterogeneous means
different elements.
7. Synchronized: ArrayList is not synchronized. That
means multiple threads can use the same ArrayList objects
simultaneously.
8. Random Access: ArrayList implements random access because
it uses an index-based structure. Therefore, we can get, set,
insert, and remove elements of the array list from any
arbitrary position.
9. Performance: In ArrayList, manipulation is slow because if any
element is removed from ArrayList, a lot of shifting takes
place.
For example, if an array list has 500 elements and we remove
50th elements then the 51st element will try to acquire that
50th position, and likewise all elements. Thus, it consumes a
lot of time-shifting.
Java ArrayList Constructor
• Java ArrayList class provides three constructors for creating an
object of ArrayList. They are as:
• ArrayList()
• ArrayList(int initialCapacity)
• ArrayList(Collection c)
• Creating an object of ArrayList class in Java is very simple.
First, we will declare an array list variable and call the array list
constructor to instantiate an object of ArrayList class and then
assign it to the variable.
• We can create an object of ArrayList class in java by using any
one of three constructors.
1. The syntax for creating an instance of ArrayList class is as:
ArrayList al = new ArrayList();
It creates an empty ArrayList with a default initial capacity of 10. In this
array list, we can store only 10 elements.
• Suppose we insert the 11th element at 10th position into an array
list, what will happen internally?
• Once ArrayList is reached its maximum capacity, the ArrayList class
automatically creates a new array with a larger capacity.
New capacity = (current capacity*3/2) + 1 = 10*3/2 + 1 = 16
• After creating a new array list with a larger capacity, all the existing
elements are copied into the new array list and then adds the new
element into it. ArrayList class reassigns the reference to the new
array objects as shown in the above figure.
• The old default array list with the collection of objects is
automatically gone into the garbage collection. Similarly, If we try to
insert 17th element, new capacity= 16*3/2 +1 = 25.
2. We can also initialize the capacity at the time of
creating ArrayList object. The syntax for creating an
instance of ArrayList class with initial capacity is as:
ArrayList al = new ArrayList(int initialCapacity);
It creates an empty ArrayList with initial capacity. If you
know the initial capacity, you can directly use this
method. Thus, we can improve the performance of the
system by default.
• For example, suppose our requirement is to add 500
elements in the array list, we will create ArrayList
object like this:
ArrayList list2 = new ArrayList(500);
3. We can also create an object of ArrayList class by
initializing a collection of elements into it. The
syntax is as follow:
ArrayList al = new ArrayList(Collection c);
It creates an ArrayList object by initializing
elements of collection c.
For example:
ArrayList list3 = new ArrayList(list1);
// list1 is elements of collection.
Java ArrayList Initialization

• There are three methods to initialize the array list in Java.


They are as follows:
1. Using Arrays.asList:
The syntax to initialize an ArrayList using as List() method is as
follows:
ArrayList<Type> list = new ArrayList<Type>(Arrays.asList(Object
o1, Object o2, .. so on));
For example:
ArrayList<String> ar = new ArrayList<String>(Arrays.asList("A",
"B", "C"))
2: Using normal way: This is a popular way to initialize ArrayList
in java program. The syntax to initialize array list is as:
ArrayList<Type> obj = new ArrayList<Type>();
obj.add("Obj o1");
obj.add("Obj o2");
and so on.
3. Using Anonymous Inner class: The syntax for initialization of
ArrayList in java using anonymous inner class is as:
ArrayList<Type> arl = new Arraylist<Type>()
{{
add(Object o1);
add(Object o2);
add(Object o3);
........
. . . . . . . }};
Methods of ArrayList class
1) add( Object o): This method adds an object o to the
arraylist.
obj.add("hello");
This statement would add a string hello in the arraylist at
last position.
2) add(int index, Object o): It adds the object o to the
array list at the given index.
obj.add(2, "bye");
It will add the string bye to the 2nd index (3rd position as
the array list starts with index 0) of array list.
3) remove(Object o): Removes the object o from
the ArrayList.
obj.remove("Chaitanya");
This statement will remove the string “Chaitanya”
from the ArrayList.
4) remove(int index): Removes element from a
given index.
obj.remove(3);
It would remove the element of index 3 (4th
element of the list – List starts with 0).
5) set(int index, Object o): Used for updating an element. It replaces
the element present at the specified index with the object o.
obj.set(2, "Tom");
It would replace the 3rd element (index =2 is 3rd element) with the
value Tom.
6) int indexOf(Object o): Gives the index of the object o. If the
element is not found in the list then this method returns the value -
1.
int pos = obj.indexOf("Tom");
This would give the index (position) of the string Tom in the list.
7) Object get(int index): It returns the object of list which is present at
the specified index.
String str= obj.get(2);
8) int size(): It gives the size of the ArrayList – Number of
elements of the list.
int numberofitems = obj.size();
9) boolean contains(Object o): It checks whether the given
object o is present in the array list if its there then it returns
true else it returns false.
obj.contains("Steve");
It would return true if the string “Steve” is present in the list
else we would get false.
10) clear(): It is used for removing all the elements of the
array list .The below code will remove all the elements of
ArrayList whose object is obj.
obj.clear();
Example Program for ArrayList
import java.util.*;
class ArrayListDemo {
public static void main(String[] args)
{
ArrayList a=new ArrayList();
a.add("A");
a.add(10);
a.add("A");
a.add(null);
System.out.println(a);//[A,10,A,null]
a.remove(2);
System.out.println(a);//[A,10,null]
a.add(2,"m");
a.add("n");
System.out.println(a);//[A,10,m,null,n]
}}
• Usually we can use collection to hold and transfer
objects to provide support for this requirement.
• ArrayList and Vector classes implements
RandomAccess interface so that any random
element we can access with the same speed.
• RandomAccess interface present in util package
and doesn’t contain any methods. It is a marker
interface.
• ArrayList is the best choice if our frequent
operation is retrieval.
• ArrayList is the worst choice if our frequent
operation is insertion (or) deletion in the middle
because it requires several internal shift
operations
How do we manually increase or decrease current
capacity of ArrayList?
1. ensureCapacity(): This method is used to increase the
current capacity of ArrayList. Since the capacity of an array
list is automatically increased when we add more elements.
But to increase manually, ensureCapacity() method of
ArrayList class is used.
2. trimTosize(): The trimTosize() method is used to trim the
capacity of ArrayList to the current size of ArrayList.
ArrayList<String> list = new ArrayList<String>();
// Here, list can hold 10 elements.(Default initial capacity).
list.ensureCapacity(20); // Now it can hold 20 elements.
list.trimTosize();
Iterators in Java

• Iterators in Java are used to retrieve the elements one by one


from a collection object. They are also called cursors in java.
• Let’s understand this concept with a realtime example.
• Suppose that there are 20 apples in a box. If I ask you how will
you eat all these 20 apples? one by one, or all apples at once
time.
• I hope that your answer will be definitely one by one. That is,
you will eat the first apple. After that, you will eat the second
apple, and so on.
• Similarly, you assume that box is a collection, and apples in
the box are elements of the collection. So if we want to get
these elements one by one, we will require some iterators or
cursors to retrieve elements one by one from the collection
object.
Types of Iterators in Java

There are four types of iterators or cursors available in Java. They are as follows:
Enumeration
Iterator
ListIterator
Spilterator
Enumeration in Java
• Enumeration is the first iterator that was introduced in Java 1.0
version. It is located in java.util package. It is a legacy interface that
is implemented to get elements one by one from the legacy
collection classes such as Vector and Properties.
• Legacy classes are those classes that are coming from the first
version of Java. Early versions of Java do not include collections
framework. Instead, it defined several classes and one interface for
storing objects.
• When collections came in the Java 1.2 version, several of the
original classes were re-engineered to support the collection
interfaces.
• Thus, they are fully compatible with the framework. These old
classes are known as legacy classes. The legacy classes defined by
java.util are Vector, Hashtable, Properties, Stack, and Dictionary.
There is one legacy interface called Enumeration.
• Enumeration is read-only. You can just read data from the vector.
You cannot remove it from the vector using Enumeration.
How to create Enumeration object in
Java?
• Since enumeration is an interface so we cannot create an
object of enumeration directly. We can create an object of
enumeration by calling elements() method of the Vector class.
• The syntax for creating an object of enumeration in java is as
follows:
• Syntax:
public Enumeration elements() // Return type is Enumeration.
For example:
Enumeration e = v.elements(); // Here, v is a vector class object.
Methods of Enumeration in Java
• The Enumeration interface defines the following two
methods. They are as follows:
1. public boolean hasMoreElements(): When this method is
implemented, hasMoreElements() will return true If there are
still more elements to extract and false if all the elements
have been enumerated.
2. public Object nextElement(): The nextElement() method
returns next element in the enumeration. It will throw
NoSuchElementException when the enumeration is complete.
Example
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationTest
{
public static void main(String[] args)
{ // Create an object of vector class using generic.
Vector<Integer> v = new Vector<Integer>();
for(int i=0; i<=10; i++)
{
v.addElement(i);
}
System.out.println(v);
Enumeration e = v.elements();
while(e.hasMoreElements())
{
// Direct type casting in one step.
Integer i = (Integer)e.nextElement();
System.out.println(i);
}
Enumeration en = v.elements();
while(en.hasMoreElements())
{ Integer it = (Integer)en.nextElement();
if(it % 2 == 0)
{ System.out.println(it);
}}}}
• Output:
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
0 1 2 3 4 5 6 7 8 9 10 0 2 4 6 8 10
• There are many limitations of using enumeration interface
in java. They are as follows:
1. Enumeration concept is applicable for only legacy class.
Hence, it is not a universal cursor.
2. We can get only read operation by using the
enumeration. We cannot perform the remove operation.
3. We can iterate using enumeration only in the forward
direction.
4. Java is not recommended to use enumeration in new
projects.
To overcome these limitations, We should go for the next level
Iterator concept in Java.
Iterator in Java
• An iterator in Java is a special type of object that provides
sequential (one by one) access to the elements of a
collection object.
• In simple words, it is an object that allows us to get and
process one element at a time. It is introduced in Java 1.2
Collections Framework.
• An Iterator object implements Iterator interface which is
present in java.util.Iterator package. Therefore, to use an
Iterator, you must import either java.util.Iterator or
java.util.*.
• Iterator in Java is used in the Collection Framework to
retrieve elements sequentially (one by one). It is
called universal Iterator or cursors.
• It can be applied to any collection object. By using Iterator,
we can perform both read and remove operations.
How to create Iterator object in Java?
• Iterator object can be created by calling iterator() method
which is present in the iterable interface. The general syntax
for creating Iterator object is as follows:
a) Iterator itr = c.iterator(); // c is any collection object.
b) Iterator<Type> itr = c.iterator(); // Generic type.
For example:
Iterator<String> itr = c.iterator();
Iterator<Integer> itr = c.iterator();
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorTest
{
public static void main(String[] args)
{
ArrayList<String> al = new ArrayList<String>();
// Adding elements in the array list.
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
al.add("F");
Iterator<String> itr = al.iterator();
while (itr.hasNext())
{
String str = itr.next();
System.out.print(str + " ");
}}}
LinkedList in Java
• LinkedList in Java is a linear data structure that uses a doubly linked
list internally to store a group of elements.
• A doubly linked list consists of a group of nodes that together
represents a sequence in the list. It stores the group of elements in
the sequence of nodes.
• Each node contains three fields: a data field that contains data
stored in the node, left and right fields contain references or
pointers that point to the previous and next nodes in the list.
• A pointer indicates the addresses of the next node and the previous
node. Elements in the linked list are called nodes.
• Since the previous field of the first node and the next field of the
last node do not point to anything, we must set it with the null
value.
• LinkedList in Java is a very convenient way to store elements (data).
When we store a new element in the linked list, a new node is
automatically created.
• Its size will grow with the addition of each and every
element. Therefore, its initial capacity is zero. When an
element is removed, it will automatically shrink.
• Adding elements into the LinkedList and removing
elements from the LinkedList are done quickly and take the
same amount of time (i.e. constant time).
• So, it is especially useful in situations where elements are
inserted or removed from the middle of the list.
• In the Linked List, the elements are not stored in the
consecutive memory location. An element (often called
node) can be located anywhere in the free space of the
memory by connecting each other using the left and right
sides of the node portion.
• Thus, it avoids the rearrangement of elements required but
requires that each element is connected to the next and
previous by a link.
• Therefore, a LinkedList is often a better choice if elements are
added or removed from intermediate locations within the list.
• The right side of the node contains the address of the next
element and the left side of the node contains the address of
the previous element in the list.
Java LinkedList Constructors
• Like ArrayList class, Java LinkedList class consists of two
constructors.
1.LinkedList() - It is used to create an empty LinkedList object.
2.LinkedList(Collection c) - It is used to construct a list containing
the elements of the given collection.

We can create an empty linked list object for storing String type
elements (objects) as:
LinkedList<String> llist = new LinkedList<String>(); // An empty
list.
Features of LinkedList class
The main features of the Java LinkedList class are as
follows:
1. The underlying data structure of LinkedList is a doubly
LinkedList data structure. It is another concrete
implementation of the List interface like an array list.
2. Java LinkedList class allows storing duplicate elements.
3. Null elements can be added to the linked list.
4. Heterogeneous elements are allowed in the linked list.
5. Java LinkedList is not synchronized. So, multiple
threads can access the same LinkedList object at the
same time. Therefore, It is not thread-safe. Since
LinkedList is not synchronized. Hence, its operation is
faster.
6. Insertion and removal of elements in the LinkedList are fast because,
in the linked list, there is no shifting of elements after each adding
and removal. The only reference for next and previous elements
changed.
7. LinkedList is the best choice if your frequent operation is insertion or
deletion in the middle.
8. Retrieval (getting) of elements is very slow in LinkedList because it
traverses from the beginning or ending to reach the element.
9. The LinkedList can be used as a “stack“. It has pop() and push()
methods which make it function as a stack.
10. Java LinkedList does not implement random access interface. So,
the element cannot be accessed (getting) randomly. To access the
given element, we have to traverse from the beginning or ending to
reach elements in the LinkedList.
11. We can iterate linked list elements by using ListIterator.
How does Insertion work in Java LinkedList?
In the Java LinkedList, we can perform insertion (addition) operations without
affecting any of data items already stored in the list. Let’s take an example to
understand this concept.
1. Let us assume that our initial LinkedList has the following data as shown in the
below figure.
2. Now we will perform insertion operation on this linked list. We
will add an element G at index position 2 using add() method.
The syntax for adding element G is as follow:
linkedlist.add(2,"G");
When the insertion operation takes place in the linked list,
internally, LinkedList will create one node with G element at
anywhere available space in the memory and changes the
next and previous pointer only without shifting of any
element in the list.
How does Deletion work in Java LinkedList?
1. Let us assume that our initial LinkedList has the following data.
2. We will perform deletion operations on this LinkedList.
Suppose we want to remove or delete element B from index
position 1. The syntax to delete element B is as follows:
• linkedlist.remove(1);When deletion operation takes place, the
node with element B is deleted with changing the next and
previous pointer. The deleted node becomes unused memory.
• Therefore, Java will clean up the unused memory space using
the garbage collection.
LinkedList Methods in Java
SN Method Description
It is used to add the specified element
1. boolean add(Object o)
to the end of a list.
It is used to insert the specified
2. void add(int index, Object o) element at the specified position in a
list.
It is used to add all of the elements in
3. boolean addAll(Collection c) the specified collection to the end of
this list
It is used to add all the elements of the
4. boolean addAll(int index, Collection c) specified collection at specified index
position in the list.
It is used to remove or delete all the
5. void clear()
elements from a list.
It returns true if a list contains a
6. boolean contains(Object o)
specified element.
It is used to get the number of
7. int size()
elements in a list.
SN Method Description
It returns an array containing all the
8. Object[] toArray()
elements in a list in proper sequence
This method is used to return a shallow copy
9. Object clone()
of an ArrayList.
This method is used to remove the first
10. boolean remove(Object o) occurrence of the specified element in the
linked list.
This method is used to remove the element
11. Element remove(int index)
at the specified position in the linked list.
This method is used to retrieve the first
12. Element element()
element of the linked list.
It is used to get the element at the specified
13. E get(int index)
position in a list.
It is used to replace the element at the
14. Element set(int index, E element) specified position in a list with the specified
element.
SN Method Description

It is used to get the index of the


first occurrence of the specified
15. int indexOf(Object o) element in the list. It returns -1 if
the list does not contain any
element.

It is used to get the index of the


last occurrence of the specified
16. int lastIndexOf(Object o)
element in a list. It returns -1 if the
list does not contain any element.

This method returns an iterator


17. Iterator iterator() over the elements in a proper
sequence in the linked list.

This method returns a list-iterator


ListIterator listIterator(int of the elements in a proper
18.
index) sequence, starting at the specified
position in the list.
// Java program to demonstrate the
// creation of list object using the
// LinkedList class

import java.io.*;
import java.util.*;

class List1 {
public static void main(String[] args)
{
// Size of the LinkedList
int n = 5;

// Declaring the List with initial size n


List<Integer> ll = new LinkedList<Integer>();

// Appending the new elements


// at the end of the list
for (int i = 1; i <= n; i++)
ll.add(i);
// Printing elements
System.out.println(ll);

// Remove element at index 3


ll.remove(3);

// Displaying the list after deletion


System.out.println(ll);

// Printing elements one by one


for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}
}
What is best case scenario to use LinkedList in
Java application?

• Java LinkedList is the best choice to use when your frequent


operation is adding or removing elements in the middle of the list
because the adding and removing of elements in the linked list is
faster as compared to ArrayList.
• Let’s take a realtime scenario to understand this concept. Suppose
there are 100 elements in the ArrayList. If we remove the 50th
element from the ArrayList, 51st element will go to 50th position,
52nd element to 51st position, and similarly for other elements that
will consume a lot of time for shifting. Due to which the
manipulation will be slow in ArrayList.
• But in the case of linked list, if we remove 50th element from the
linked list, no shifting of elements will take place after removal.
Only the reference of the next and previous node will change.
• Moreover, LinkedList can be used when we need a stack (LIFO) or
queue (FIFO) data structure by allowing duplicates.
What is worst case scenario to use LinkedList?
• Java LinkedList is the worst choice to use when your frequent operation is
retrieval (getting) of elements from the linked list because retrieval of elements is
very slow in the LinkedList as compared to ArrayList.
• LinkedList does not implement Random Access Interface. Therefore, an element
cannot be accessed (getting) randomly. We will have to traverse from the
beginning or ending to reach elements in the linked list.
• Let us consider a realtime scenario to understand this concept.
• Assume that there are ten elements in the list. Suppose that LinkedList accesses
the first element in one second from the list and retrieves the element.
• Since the address of second element is available in the first node. So, it will take
two seconds time to access and get the second element.
• Similarly, if we want to get 9th element from the list then LinkedList will take 9 sec
time to get element. Why?
• This is because the address of 9th element is available in 8th node. The address of
8th node is available in 7th node and so on.
• But if there are one crore elements in the list and we want to get 50th lakh
element from the list, may be linked list will take one year time to access and
getting 50th lakh element.
• Therefore, LinkedList is the worst choice for the retrieval or searching of elements
from the linked list.
• In this case, ArrayList is the best choice to use for getting elements from the list
because ArrayList implements random access interface.
Vector
• Vector is a class which is implemented in the collection
framework implements a growable array of objects. Vector
implements a dynamic array that means it can grow or shrink
as required. Like an array, it contains components that can be
accessed using an integer index. Vectors basically fall in legacy
classes but now it is fully compatible with collections.
// Java program to demonstrate the
// creation of list object using the
// Vector class

import java.io.*;
import java.util.*;

class Vector1 {
public static void main(String[] args)
{
// Size of the vector
int n = 5;

// Declaring the List with initial size n


List<Integer> v = new Vector<Integer>(n);

// Appending the new elements


// at the end of the list
for (int i = 1; i <= n; i++)
v.add(i);
// Printing elements
System.out.println(v);

// Remove element at index 3


v.remove(3);

// Displaying the list after deletion


System.out.println(v);

// Printing elements one by one


for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}
• Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235
Stack
• Stack is a class which is implemented in the collection
framework and extends the vector class models and
implements the Stack data structure. The class is based on the
basic principle of last-in-first-out. In addition to the basic push
and pop operations, the class provides three more functions
of empty, search and peek
// Java program to demonstrate the
// creation of list object using the
// Stack class

import java.io.*;
import java.util.*;

class Stack1 {
public static void main(String[] args)
{
// Size of the stack
int n = 5;

// Declaring the List


List<Integer> s = new Stack<Integer>();

// Appending the new elements


// at the end of the list
for (int i = 1; i <= n; i++)
s.add(i);
// Printing elements
System.out.println(s);

// Remove element at index 3


s.remove(3);

// Displaying the list after deletion


System.out.println(s);

// Printing elements one by one


for (int i = 0; i < s.size(); i++)
System.out.print(s.get(i) + " ");
}
}
Features of Stack class
• There are several features of stack in Java that are as
follows:
1. Stack is a group of elements with “last-in, first-out”
retrieval.
2. In the Java stack, all operations take place at the top of
the stack.
3. Push operation inserts an element to the top of stack.
4. Pop operation removes an element from the stack and
returns it.
5. Stack class is synchronized. That means it is thread-
safe.
6. Null elements are allowed into the stack.
7. Duplicate elements are allowed into the stack.
Map
• A map in Java is a container object that stores elements in the
form of key and value pairs. A key is a unique element (object)
that serves as an “index” in the map.
• The element that is associated with a key is called value. A
map stores the values associated with keys. In a map, both
keys and values must be objects and cannot be primitive
types.
• A map cannot have duplicate keys. Each key maps to only one
value. This type of mapping is called one-to-one mapping in
java.
• All keys must be unique, but values may be duplicate (i.e. the
same value can be stored to several different keys).
• A key and its associated value are called an entry that is
stored in a map as shown in the below figure. After the entry
(key/value pairs) is stored in a map, we can retrieve (get) its
value by using its key.
Key point: The main difference between maps and sets is that maps contain keys and
values, whereas sets contain only keys.
Map Interface in Java
• Map interface in Java is defined in java.util.Map package.
• It is a part of the Java collections framework but it does not
extend the collection interface.
• Java map interface is defined like this:
public interface Map<K, V> // Map is a generic.
• In this syntax, K defines the type of keys and V defines the
type of values.
• For example, a mapping of Integer keys and String values can
be represented with a Map<Integer,String>. The Map
interface provides the methods for fast retrieval, deletion, and
updating of the pair through the key.
Java Map.Entry Interface
• The Map.Entry interface enables us to work on an entry in
the map. An entry of a map is an object of type Map.Entry
interface, where Entry is an inner interface of Map interface.
• Map.Entry interface is defined in java.util.Map.Entry package.
Each Map.Entry object contains one key/value pair. Map.Entry
is a generic interface and is declared like this:
interface Map.Entry<K, V>
• There are several methods defined by Map.Entry
interface in Java. They are as follows:
1. boolean equals(Object obj): It is used to check for
equality of the specified object with the other existing
object. It returns true if the specified object obj is a
Map.Entry whose key and value are equal to that of
the existing object.
2. K getKey(): It is used to retrieve the key for a map
entry. Its return type is key.
3. V getValue(): It is used to get the value for a map entry.
Its return type is value.
4. int hashCode(): It returns hash code value for a map
entry.
5. void setValue(V value): This method is used to replace
the existing value corresponding to this entry with the
specified value and returns the replaced value.
How to create Map Object in Java?
• We can create an object of the map using any of its three
concrete classes: HashMap, LinkedHashMap, or TreeMap.
Here, we will take HashMap class constructor to create a Map
in Java.
• The general syntax to create a map object is as follows:
a) Map<K, V> map = new HashMap<>(); // It create an empty
map.
b) Map<K, V> map = new HashMap<>(Map m); // It creates a
map with initializing elements of m.
c) Map<K, V> map = new HashMap<>(int initialCapacity); // It
creates a map with initialization of initial capacity of
HashMap.
d) Map<K, V> map = new HashMap<>(int initialCapacity, float
fillRatio); // It creates a map object with initializing both initial
capacity and fill ratio of HashMap.
Java Map Example
import java.util.HashMap;
import java.util.Map;
public class AddDemo
{
public static void main(String[] args)
{ // Create a map of generic type.
Map<Integer, String> map = new HashMap<>();
// Checking map is empty or not.
boolean isEmpty = map.isEmpty();
System.out.println(" Is Map empty? " +isEmpty);
// Adding entries in the map. Call put() method to add entries in map.
map.put(101, "Red");
map.put(103, "Green");
map.put(102, "Yellow");
map.put(104, "Blue");
map.put(106, "Pink");
System.out.println("Entries in Map: " +map);
int size = map.size();
System.out.println("No. of entries in Map: " +size);
// Create another map.
Map<Integer,String> map2 = new HashMap<>();
map2.put(115, "Brown");
map2.put(120, "Purple");
map2.put(125, "Green");
map.putAll(map2);
System.out.println("Entries in updated Map: " +map);
}}
• Output:
Is Map empty? true
Entries in Map: {101=Red, 102=Yellow, 103=Green, 104=Blue,
106=Pink}
No. of entries in Map: 5
Entries in updated Map: {115=Brown, 101=Red, 102=Yellow,
103=Green, 104=Blue, 120=Purple, 106=Pink, 125=Green}
Iterating Map using Map.Entry<K,V>method
• Map.Entry<K,V> is an interface that is used to work on an
entry in the map. It returns a collection view of the map. Each
Map.Entry object contains one key/value pair.
• We will use the following methods for iteration.
1. getKey(): It is used to retrieve the key for a map entry. Its
return type is key.
2. getValue(): It is used to get the value for a map entry. Its
return type is value.
3. entrySet(): It returns a set view of entries of a map
Example
import java.util.HashMap;
import java.util.Map;
public class IterationTest4
{
public static void main(String[] args)
{
Map<Integer, String> map = new HashMap<>();
map.put(101, " John");
map.put(202, " Ricky");
map.put(303, " Deep");
map.put(404, " Mark");
map.put(505, " Maya");
for (Map.Entry<Integer,String> entry : map.entrySet())
// Iterating over entries of a map using entrySet() method.
{
System.out.println("Roll No: " + entry.getKey() + ", Name: " +
entry.getValue());
}}}

Output:
Roll No: 404, Name: Mark
Roll No: 101, Name: John
Roll No: 505, Name: Maya
Roll No: 202, Name: Ricky
Roll No: 303, Name: Deep
HashMap in Java
• HashMap<K, V> is a part of Java’s collection since Java 1.2.
This class is found in java.util package.
• In simpler terms, HashMap<K, V> is a data structure that
stores elements in the form of a key-value pair.
• These key-value pairs are also termed as an Entry of
HashMap.
• Keys are unique, and duplicate keys are not allowed.
• It stores values based on keys, and it can be accessed using
keys.
• Hashmap allows multiple null values and only one null key.
• HashMaps are non-synchronized, meaning that they are not
thread-safe. If multiple threads access the hashmap at the
same time, they will modify the map structurally.
• HashMaps are an unordered collection of key-value pairs.
They do not maintain the insertion order.
• They are much faster in terms of retrieving data as compared
to arrays and linked-list, with constant time performance for
the basic operations.
• Its initial default capacity(number of elements that can be
stored) of hashmap is 16, and the default load factor is 0.75.
CONSTRUCTORS IN HASHMAP
• There are four constructors of the hashmap, all of which have
public access specifiers.
1. Hashmap()
• It is the default constructor that creates an instance of a
hashmap with the initial capacity of
• 16 and load factor 0.75.
HashMap<K,V> hm = new HashMap<K,V>();
2. HashMap(int initialCapacity)
• This constructor creates an instance of a hashmap with the
specified initial capacity and
• default load factor 0.75.
HashMap<K,V> hm = new HashMap<K,V>(int initialCapacity);
3. HashMap(int initialCapacity, float loadFactor)
• This constructor creates an instance of a hashmap with the
specified initial capacity and the
• specified load factor.
HashMap<K,V> hm = new HashMap<K,V>(int initialcapacity, float
loadfactor);
4. HashMap(Map map)
• This constructor creates an instance of a hashmap with
similar mappings as the given Map.
HashMap<K,V> hm = new HashMap<K,V>(Map m);
Example-1
import java.io.*;
import java.util.*;
public class Hashmap
{
public static void main(String args[])
{
HashMap<String, Integer> hm = new HashMap<String, Integer>(5,0.75f);
hm.put("Red",1);
hm.put("Blue",2);
hm.put("Green",3);
hm.put("Yellow",4);
System.out.println(hm);
}}
Example-2
import java.io.*;
import java.util.*;
public class Hashmap
{
public static void main(String args[])
{ Map<String, Integer> hm = new HashMap<String, Integer>();
hm.put("Red",1);
hm.put("Blue",2);
hm.put("Green",3);
hm.put("Yellow",4);
System.out.println(hm);
HashMap<String, Integer> hm1 = new HashMap<String, Integer>(hm);
System.out.println(hm1);
}}
• Output :
{Red=1, Blue=2, Yellow=4, Green=3}
{Red=1, Blue=2, Yellow=4, Green=3}
Methods of HashMap
• These are various important hashmap class methods.
1.put(): java.util.HashMap.put() plays role in associating the
specified value with the specified key in this map. If the map
previously contained a mapping for the key, the old value is
replaced.
Syntax:
public V put(K key,V value)
2.get(): java.util.HashMap.get()method returns the value to
which the specified key is mapped, or null if this map contains
no mapping for the key.
Syntax:
public V get(Object key)
3. isEmpty(): java.util.HashMap.isEmpty() method returns true if the
map contains no key-value mappings.
Syntax:
public boolean isEmpty()
4. size(): java.util.HashMap.size() returns the number of key-value
mappings in this map.
Syntax:
public int size()
5. The remove(K) method takes the key as the argument and deletes
the entry for the given key if it is present on the map. We also have
one more remove(K, V) method to delete the entry.
6. Access one particular value associated with a key using get(K)
The value present in a hashmap can be accessed using the
method get(K). The key must be passed in the argument, and the
value stored in that key will be fetched.
7. Access only the keys of elements
If you want to retrieve only the set of keys, the keySet() method will
return just the set of keys in hashmaps.
8. Access only the values of elements
The values() method helps to obtain the set of values.
9. Access the entries of HashMap
The entrySet() method will return the set of entries(<K, V>) in a
hashmap.
10. Traverse the HashMap
After knowing how to access the elements in a hashmap, let us see
how to iterate or traverse the hashmap.
The idea is to iterate over the set of entries using the for-each loop and
then access the key and values in an entry using
the getKey() and getValue() methods.
We use Map.Entry(K, V) that allows us to access the entries of a map.
11. Update the value
• If you want to update the value stored in a given key, you can
either use put(K, V) or
• replace(k,v) method.
import java.io.*;
import java.util.*;
public class Hashmap
{
public static void main(String args[])
{
HashMap<String, Integer> hm = new HashMap<String,
Integer>();
hm.put("Red",1);
hm.put("Blue",2);
hm.put("Green",3);
hm.put("Yellow",4);
System.out.println(hm);
System.out.println(hm.entrySet()); } }
• Output :
{Red=1, Blue=2, Yellow=4, Green=3}
[Red=1, Blue=2, Yellow=4, Green=3]
Linked HashMap
• LinkedHashMap in Java is a concrete class that is HashTable and
LinkedList implementation of Map interface. It stores entries using a
doubly-linked list.
• Java LinkedHashMap class extends the HashMap class with a linked-list
implementation that supports an ordering of the entries in the map.
• LinkedHashMap in Java was added in JDK 1.4 version. It is exactly the
same as HashMap (including constructors and methods) except for the
following differences:
1. The underlying data structure of HashMap is HashTable whereas, the
underlying data structure of LinkedHashMap is HashTable and LinkedList
(Hybrid data structure).
2. Insertion order is not preserved in the HashMap because it is based on
the hashCode of Key. But in the case of LinkedHashMap, the insertion
order of elements is preserved because it is based on the Key insertion
order, that is, the order in which keys are inserted in the map.
3. HashMap was introduced in Java 1.2 version whereas, LinkedHashMap
was introduced in Java 1.4 version.
LinkedHashMap class declaration
• LinkedHashMap is a generic class that is present in
java.util.LinkedHashMap package. It has the following
declaration.
public class LinkedHashMap<K,V> extends HashMap<K,V>
implements Map<K,V>
• Here, K defines the type of keys, and V defines the type of
values.
Features of LinkedHashMap in Java
• There are several features of LinkedHashMap in Java that should
keep in mind. They are as follows:
1. The underlying data structure of LinkedHashMap is HashTable
and LinkedList.
2. Java LinkedHashMap maintains the insertion order. The entries in
Java LinkedHashMap can be retrieved either in the order in which
they were inserted into the map (known as insertion order) or in
the order in which they were last accessed, from least to most
recently accessed.
3. LinkedHashMap contains unique elements. It contains values based
on keys.
4. LinkedHashMap allows only one null key but can have multiple null
values.
5. LinkedHashMap in Java is non synchronized. That is,
multiple threads can access the same LinkedHashMap object
simultaneously.
6. The default initial capacity of LinkedHashMap class is 16 with a load
factor of 0.75.
Constructors of Java LinkedHashMap class
• Java LinkedHashMap class has the following constructors.
They are as follows:
1. LinkedHashMap(): This constructor is used to create a default
LinkedHashMap object. It constructs an empty insertion-
ordered LinkedHashMap object with the default initial
capacity 16 and load factor 0.75.
• The general syntax to construct default LinkedHashMap object
is as follows:
• LinkedHashMap lhmap = new LinkedHashMap(); or,
LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(); //
Generic form
2. LinkedHashMap(int initialCapacity): It is used to create an
empty insertion-ordered LinkedHashMap object with the
specified initial capacity and a default load factor of 0.75. The
general syntax in generic form is as follows:
LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(int
initialCapacity);
3. LinkedHashMap(int initialCapacity, float loadFactor): It is
used to create an empty insertion-ordered LinkedHashMap
object with the specified initial capacity and load factor. The
general syntax in generic form is given below:
LinkedHashMap<K,V> lhmap = new LinkedHashMap<>(int
initialCapacity, float loadFactor);
For example: LinkedHashMap<String, Integer> lhmap = new
LinkedHashMap<>(16, 0.75f);
4. LinkedHashMap(Map m): This constructor is used to create an
insertion-ordered LinkedHashMap object with the elements
from the given Map m.
5. LinkedHashMap(int initialCapacity, float loadFactor, boolean
accessOrder): This constructor is used to create an empty
LinkedHashMap instance with the specified initial capacity,
load factor, and ordering mode.
• If accessOrder is true, access-order is used. If it is false, the
insertion order is used.
• The general syntax to create LinkedHashMap object with
three arguments of constructor is as follows:
LinkedHashMap<K,V> lhmap = new LinkedHashMap<int
initialCapacity, float loadFactor, boolean accessOrder>();
For example:
1.LinkedHashMap<String, String> lhmap = new
LinkedHashMap<>(16, 0.75f, true); // For access order.
2.LinkedHashMap<String, String> lhmap = new
LinkedHashMap<>(16, 0.75f, false); // For insertion order
LinkedHashMap Methods in Java
• The methods of LinkedHashMap are exactly the same as HashMap
class methods, except for one method that is added by
LinkedHashMap. This method is removeEldestEntry().
• The general syntax for this method is as follows:
protected boolean removeEldestEntry(Map.Entry<K,V> e)
• The parameter e is the least recently added entry in the map, or if it
is an access-ordered map, the least recently accessed entry.
• This method returns true if the map removes this eldest (oldest)
entry. If this entry is retained, or not removed, this method returns
false.
• The removeEldestEntry() method is called by put() and putAll() after
adding a new entry into the map. It helps to remove the eldest
entry each time when a new entry is added.
• This method is useful if the map represents a cache. It allows the
map to reduce memory consumption by deleting stale entries.
Example
import java.util.LinkedHashMap;
public class LinkedHashMapEx1
{
public static void main(String[] args)
{ // Create a LinkedHashMap instance.
LinkedHashMap<String, Integer> lhmap = new
LinkedHashMap<>();
// Checking the size of linked hash map before adding entries.
int size = lhmap.size();
System.out.println("Size of LinkedHashMap before adding
entries: " +size);
// Checking linked hash map is empty or not before adding
//entries.
boolean isEmpty = lhmap.isEmpty();
System.out.println("Is LinkedHashMap empty: " +isEmpty);
// Adding entries in linked hash map.
lhmap.put("John", 30);
lhmap.put("Peter", 25);
lhmap.put("Ricky", 23);
lhmap.put("Deep", 28);
lhmap.put("Mark", 32);
System.out.println("Display entries in LinkedHashMap");
System.out.println(lhmap); int size2 = lhmap.size();
System.out.println("Size of LinkedHashMap after adding
entries: " +size2);
// Adding null as key and value.
lhmap.put(null, null);
System.out.println(lhmap);
}
• Output:
Size of LinkedHashMap before adding entries: 0
Is LinkedHashMap empty: true
Display entries in LinkedHashMap
{John=30, Peter=25, Ricky=23, Deep=28, Mark=32}
Size of LinkedHashMap after adding entries: 5
{John=30, Peter=25, Ricky=23, Deep=28, Mark=32, null=null}
• When to use LinkedHashMap in Java?
• LinkedHashMap can be used when you want to preserve the
insertion order. Java LinkedHashMap is slower than HashMap
but it is suitable when more number of insertions and
deletions happen.
• Which implementation is better to use: HashMap or
LinkedHashMap?
• Both HashMap and LinkedHashMap classes provide
comparable performance but HashMap is a natural choice if
the ordering of elements is not an issue.
• Adding, removing, and finding entries in a LinkedHashMap is
slightly slower than in HashMap because it needs to maintain
the order of doubly linked list in addition to the hashed data
structure.
TreeMap in Java
• TreeMap in Java is a concrete class that is a red-black tree based
implementation of the Map interface.
• It provides an efficient way of storing key/value pairs in sorted
order automatically and allows rapid retrieval. It was added in JDK
1.2 and present in java.util.TreeMap.
• A TreeMap implementation provides guaranteed log(n) time
performance for checking, adding, retrieval, and removal
operations.
• The two main difference between HashMap and TreeMap is that
HashMap is an unordered collection of elements while TreeMap
is sorted in the ascending order of its keys. The keys are sorted
either using Comparable interface or Comparator interface.
• HashMap allows only one null key while TreeMap does not allow
any null key.
TreeMap class declaration

• TreeMap is a generic class that can be declared as follows:

public class TreeMap<K,V> extends AbstractMap<K,V>


implements NavigableMap<K,V>, Cloneable, Serializable
• Here, K defines the type of keys, and V defines the type of
values.
Important Features of TreeMap
There are several important features of TreeMap in Java that should be
kept in mind. They are as follows:
1. The underlying data structure of Java TreeMap is a red-black binary
search tree.
2. TreeMap contains only unique elements.
3. TreeMap cannot have a null key but can have multiple null values.
4. Java TreeMap is non synchronized. That means it is not thread-safe.
We can create a synchronized version of map by calling
Collections.synchronizedMap() on the map.
5. TreeMap in Java maintains ascending order. The mappings are sorted
in treemap either according to the natural ordering of keys or by a
comparator that is provided during the object creation of TreeMap
depending upon the constructor used.
6. Java TreeMap determines the order of entries by using
either Comparable interface or Comparator class.
7. The iterator returned by TreeMap is fail-fast. That means we cannot
modify map during iteration.
Constructors of TreeMap class in Java
• Java TreeMap defines the following constructors. They are as
follows:
1. TreeMap(): This constructor is used to create an empty TreeMap
that will be sorted according to the natural order of its key. All
keys added to tree map must implement Comparable interface.
The compareTo() method in the Comparable interface is used to
compare keys in the map. If you put a string key into the map
whose type is an integer, the put() method will throw an
exception named ClassCastException.
2. TreeMap(Comparator c): This form of constructor is used to
create an empty tree-based map. All keys inserted in the map
will be sorted according to the given Comparator c.
The compare() method in the comparator is used to order the
entries in the map based on keys.
3. TreeMap(Map m): This form of constructor is used to initialize
a tree map with entries from Map m that will be sorted
according to the natural order of the keys.
4. TreeMap(SortedMap sm): This constructor is used to initialize
a treemap with the entries from the SortedMap sm which will
be sorted according to the same ordering as sm.
Methods of Java TreeMap class
• TreeMap class in java provides a variety of methods to perform different
tasks. They are as follows:
1. void clear(): This method removes all objects (entries) from the tree map.
2. V put(K key, V value): This method is used to insert a key/value pair in the
tree map.
3. void putAll(Map m): It is used to add key/value pairs from Map m to the
current tree map.
4. V remove(Object key): It is used to remove the key-value pair of the specified
key from the tree map.
5. V get(Object key): This method is used to retrieve the value associated with
key. If key is null, it will throw NullPointerException.
6. K firstKey(): It is used to retrieve key of first entry in the sorted order from
the map. If the tree map is empty, it will throw NoSuchElementException.
7. K lastKey(): It is used to retrieve key of first entry in the sorted order from the
map. If the tree map is empty, it will throw NoSuchElementException.
8. boolean containsKey(Object key): This method returns true if the tree map
contains a particular key.
9. boolean containsValue(Object value): This method returns true if the tree
map contains a particular value.
10. int size(): This method returns the number of entries (objects) in the tree
map.
Example
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.TreeMap;
public class TreeMapEx1
{
public static void main(String[] args)
{ // Create a HashMap.
HashMap<String, String> hmap = new HashMap<>();
hmap.put("R", "Red");
hmap.put("G", "Green");
hmap.put("B", "Brown");
hmap.put("O", "Orange");
hmap.put("P", "Pink");
System.out.println("Entries of HashMap: " +hmap);
// Create a TreeMap from the previous HashMap.
TreeMap<String, String> tmap = new TreeMap<>(hmap);
System.out.println("Entries in ascending order of keys: " +tmap);
// Create a LinkedHashMap.
LinkedHashMap<String, String> lhmap = new LinkedHashMap<>();
lhmap.put("R", "Red");
lhmap.put("G", "Green");
lhmap.put("B", "Brown");
lhmap.put("O", "Orange");
lhmap.put("P", "Pink");
System.out.println("Entries in LinkedHashMap: " +lhmap); } }
• Output:
Entries of HashMap: {P=Pink, R=Red, B=Brown, G=Green,
O=Orange}
Entries in ascending order of keys: {B=Brown, G=Green,
O=Orange, P=Pink, R=Red}
Entries in LinkedHashMap: {R=Red, G=Green, B=Brown,
O=Orange, P=Pink}
• As you can see in the output of the
program, HashMap does not maintain the
order, LinkedHashMap maintains the order of entries
as we inserted, while TreeMap sorted entries in
ascending order of its keys.
Type Wrappers
• Wrapper classes provide a way to use primitive data types
(int, boolean, etc..) as objects.
Primitive Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
boolean Boolean
char Character
• Sometimes you must use wrapper classes, for example when working
with Collection objects, such as ArrayList, where primitive types
cannot be used (the list can only store objects).
• Example
1.ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid
2.ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid
Creating Wrapper Objects
• To create a wrapper object, use the wrapper class instead of
the primitive type.
public class Main
{
public static void main(String[] args)
{
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt);
System.out.println(myDouble);
System.out.println(myChar);
}}
• The following methods are used to get the value associated
with the corresponding wrapper object:
intValue()
byteValue(),
shortValue(),
longValue(),
floatValue(),
doubleValue(),
charValue(),
booleanValue().
public class Main
{
public static void main(String[] args)
{
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
System.out.println(myInt.intValue());
System.out.println(myDouble.doubleValue());
System.out.println(myChar.charValue());
}}
• Another useful method is the toString() method, which is used
to convert wrapper objects to strings.
• In the following example, we convert an Integer to a String,
and use the length() method of the String class to output the
length of the "string":
public class Main
{
public static void main(String[] args)
{ Integer myInt = 100;
String myString = myInt.toString();
System.out.println(myString.length());
}}
Sorting collections using utility methods
• We can sort the collection or arrays in Java using callback
method like sort from collections utility class and arrays utility
class.
• Sorting arrays and collections containing primitive types of
data :
• Sorting collections containing Primitive does not require extra
effort apart from using existing functions .
For arrays sorting we use the method Arrays.sort();
For collection sorting we use the method Collections.sort();
Example
package com.kb.collections_sorting;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class PrimitiveSorting
{
public static void main(String[] args)
{
int[] arrayOfIntegers = {3,1,0,7};
Arrays.sort(arrayOfIntegers);
System.out.println("sorted array of integers are ");
System.out.println(Arrays.toString(arrayOfIntegers));
String[] arrayOfStrings = {"hai","how","are","you"};
System.out.println("sorted array of strings are ");
Arrays.sort(arrayOfStrings);
System.out.println(Arrays.toString(arrayOfStrings));
List stringList = new ArrayList();
stringList.add("java");
stringList.add("unix");
stringList.add("shell script");
stringList.add("j2ee");
Collections.sort(stringList);
System.out.println("sorted list of integers are ");
for (Object element : stringList)
{
System.out.println(element);
}}}
equals() and hashCode contract in Java
collections
• By default, the Java super class java.lang.Object provides two
important methods for comparing
objects: equals() and hashcode(). These methods become
very useful when implementing interactions between several
classes in large projects.
Method Definition and Default Implementation

• equals(Object obj):
a method provided by java.lang.Object that indicates whether
some other object passed as an argument is "equal to" the
current instance. The default implementation provided by the
JDK is based on memory location — two objects are equal if
and only if they are stored in the same memory address.
• hashcode():
a method provided by java.lang.Object that returns an integer
representation of the object memory address. By default, this
method returns a random integer that is unique for each
instance. This integer might change between several executions
of the application and won't stay the same.
The Contract Between equals() and hashcode()
• It is generally necessary to override the hashCode() method
whenever equals() method is overridden, so as to maintain the general
contract for the hashCode() method, which states that equal objects
must have equal hash codes.
• Whenever it is invoked on the same object more than once during an
execution of a Java application, the hashCode method must consistently
return the same integer, provided no information used
in equals comparisons on the object is modified.
This integer need not remain consistent from one execution of an
application to another execution of the same application.
• If two objects are equal according to the equals(Object) method, then
calling the hashCode method on each of the two objects must produce
the same integer result.
• It is not required that if two objects are unequal according to
the equals(java.lang.Object) method, then calling the hashCode method
on each of the two objects must produce distinct integer results.
However, the programmer should be aware that producing distinct
integer results for unequal objects may improve the performance of
hash tables.
Example
public class Student
{
private int id;
private String name;
public Student(int id, String name)
{
this.name = name;
this.id = id;
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}}
public class HashcodeEquals
{
public static void main(String[] args)
{
Student alex1 = new Student(1, "Alex");
Student alex2 = new Student(1, "Alex");
System.out.println("alex1 hashcode = " + alex1.hashCode());
System.out.println("alex2 hashcode = " + alex2.hashCode());
System.out.println("Checking equality between alex1 and
alex2 = " + alex1.equals(alex2));
}}
• Output:
alex1 hashcode = 1852704110
alex2 hashcode = 2032578917
Checking equality between alex1 and alex2 = false
• Although the two instances have exactly the
same attribute values, they are stored in
different memory locations. Hence, they are
not considered equal as per the default
implementation of equals(). The same applies
for hashcode() — a random unique code is
generated for each instance.
Overriding equals()
• For business purposes, we consider that two students are
equal if they have the same ID, so we override
the equals() method and provide our own implementation as
the following:
@Override
public boolean equals(Object obj)
{
if (obj == null)
return false;
if (!(obj instanceof Student))
return false;
if (obj == this)
return true;
return this.getId() == ((Student) obj).getId();}
• In the above implementation, we are saying that two students
are equal if and only if they are stored in the same memory
address OR they have the same ID. Now if we try to
run HashcodeEquals, we will get the following output:
alex1 hashcode = 2032578917
alex2 hashcode = 1531485190
Checking equality between alex1 and alex2 = true
• As you noticed, overriding equals() with our custom business
forces Java to consider the ID attribute when comparing
two Student objects.
Overriding hashcode()
• equals() With HashSet
• We want to store all the students in a HashSet, so we
update HashcodeEquals as the following:

public class HashcodeEquals {


public static void main(String[] args)
{
Student alex1 = new Student(1, "Alex");
Student alex2 = new Student(1, "Alex");
HashSet < Student > students = new HashSet < Student > ();
students.add(alex1);
students.add(alex2);
System.out.println("HashSet size = " + students.size());
System.out.println("HashSet contains Alex = " + students.contains(new
Student(1, "Alex")));
}}
• If we run the above test, we get the following output:
HashSet size = 2
2HashSet contains Alex = false
• Now if we try to run the same test, we get the following
output:
HashSet size = 1
HashSet contains Alex = true
• The two elements are now considered as equal and stored in
the same memory bucket, so any time you call contains() and
pass a student object holding the same hash code, the set will
be able to find the element.
• HashSet stores its elements in memory buckets. Each bucket
is linked to a particular hash code. When
calling students.add(alex1), Java stores alex1 inside a bucket
and links it to the value of alex1.hashcode(). Now any time an
element with the same hash code is inserted into the set, it
will just replace alex1. However, since alex2 has a different
hash code, it will be stored in a separate bucket and will be
considered a totally different object.
• Now when HashSet searches for an element inside it, it first
generates the element's hash code and looks for a bucket
which corresponds to this hash code.
• Here comes the importance of overriding hashcode(), so let's
override it in Student and set it to be equal to the ID so that
students who have the same ID are stored in the same bucket:
@Override
public int hashCode()
{ return id;
}
Key Points
• In order to achieve a fully working custom equality
mechanism, it is mandatory to override hashcode() each
time you override equals(). Follow the tips below and you'll
never have leaks in your custom equality mechanism:
• If two objects are equal, they MUST have the same hash
code.
• If two objects have the same hash code, it doesn't mean
that they are equal.
• Overriding equals() alone will make your business fail with
hashing data structures like: HashSet, HashMap,
HashTable ... etc.
• Overriding hashcode() alone doesn't force Java to ignore
memory addresses when comparing two objects.
AWT
• Java programming is used to develop different types of applications
like window-based applications, web applications, Enterprise
applications, or mobile applications.
• For creating standalone applications, Java AWT API is used. AWT allows
programmers to create Graphical User Interface (GUI) for a window-
based application.
• Java Abstract Window Toolkit (AWT) is an Application Program
Interface (API).
• The components used in Java AWT are platform-dependent.
• It uses recourses of the operating system that means the view of these
components is changed according to the operating system.
• Java AWT components are platform-dependent which implies that they
are displayed according to the view of the operating system.
• AWT is rarely used now days because of its platform dependent and
heavy-weight nature. AWT components are considered heavy
weight because they are being generated by underlying operating
system (OS). For example if you are instantiating a text box in AWT
that means you are actually asking OS to create a text box for you.
Features of AWT

• AWT has a set of native user interface components.


• It provides various classes for graphical representation
of components like font, shape, color.
• It provides a robust event-handling model.
• It has Layout managers which is helpful for changing
window size or screen resolution.
• It provides a large range of libraries that can be used
for designing graphics for gaming applications or
educational applications.
• It has data transfer classes through which cut and paste
operation can be performed using the local clipboard.
AWT hierarchy
Components and containers
• All the elements like buttons, text fields, scrollbars etc are known as
components. In AWT we have classes for each component .
• To have everything placed on a screen to a particular position, we have to
add them to a container.
• A container is like a screen wherein we are placing components like
buttons, text fields, checkbox etc.
• In short a container contains and controls the layout of components. A
container itself is a component (shown in the above hierarchy diagram)
thus we can add a container inside container.
• Types of containers:
As explained above, a container is a place wherein we add
components like text field, button, checkbox etc. There are four
types of containers available in AWT: Window, Frame, Dialog and
Panel. As shown in the hierarchy diagram above, Frame and Dialog
are subclasses of Window class.
Window: An instance of the Window class has no border and no
title
Dialog: Dialog class has border and title. An instance of the Dialog
class cannot exist without an associated instance of the Frame
class.
Panel: Panel does not contain title bar, menu bar or border. It is a
generic container for holding components. An instance of the Panel
class provides a container to which to add components.
Frame: A frame has title, border and menu bars. It can contain
several components like buttons, text fields, scrollbars etc. This is
most widely used container while developing an application in AWT.
Java AWT Example

• We can create a GUI using Frame in two ways:


1) By extending Frame class
2) By creating the instance of Frame class
AWT Example 1: creating Frame by
extending Frame class
import java.awt.*;
/* We have extended the Frame class here,
* thus our class "SimpleExample" would behave
* like a Frame */
public class SimpleExample extends Frame
{
SimpleExample()
{ Button b=new Button("Button!!");
// setting button position on screen
b.setBounds(50,50,50,50);
//adding button into frame
add(b);
//Setting Frame width and height
setSize(500,300);
//Setting the title of Frame
setTitle("This is my First AWT example");
//Setting the layout for the Frame
setLayout(new FlowLayout());
/* By default frame is not visible so
* we are setting the visibility to true
* to make it visible. */
setVisible(true);
}
public static void main(String args[])
{ // Creating the instance of Frame
SimpleExample fr=new SimpleExample();
}}
AWT Example 2: creating Frame by
creating instance of Frame class
import java.awt.*;
public class Example2 {
Example2()
{
//Creating Frame
Frame fr=new Frame();
//Creating a label
Label lb = new Label("UserId: ");
//adding label to the frame
fr.add(lb);
//Creating Text Field
TextField t = new TextField();
//adding text field to the frame
fr.add(t);
//setting frame size
fr.setSize(500, 300);
//Setting the layout for the Frame
fr.setLayout(new FlowLayout());
fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}}

You might also like