Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 68

YumXpress App

Packages
 A package in java is a collection of related classes and interfaces.
 In simple words a package in java is just a folder containing a collection
of or a group of classes and interfaces serving the same purpose.
 Java language itself comes with more than 225 packages and around
4500 predefined classes.
 So, java strongly recommends to every developer that he must also
create all his classes and interfaces inside packages.

Benefits of Packages
 If we are creating packages then we can store or create or store .java file
with same name in two different packages
 For examples :: we can create two packages called calender and fruit. In
both of them we create a class called Date where calender.Date represents a
Date in the calender while fruit.Date represents a popular dry fruit whose
name is Date(khajoor).

 If we create packages, we can avoid accidental overwriting of .class file.


 Only and only if a class is in a package, we can import it in another program
 Our program/projects look much organized if we save all the related classes
in their respective packages.

Standard structure of a java program


Package <package_name>;

Import ---------------------------

Import ---------------------------

class <class_name>

-------------;

-------------;

}
Creating two classes in the same package

 If two classes belong to the same packages then we do not have


import it

 We have two files with the same package as follows: -

 package mymath;

public class Num {


private int a,b,c;
void set(int a,int b)
{
this.a=a;
this.b=b;
}
void add()
{
c = a+b;
}
void display()
{
System.out.println("nos are: "+a+" "+b);
System.out.println("their sum is: "+c);
}
}

 we have another file called UseNum.java


package mymath;

import java.util.Scanner;

public class UseNum {


public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("enter the num1: ");
int a = kb.nextInt();
System.out.print("enter the num2: ");
int b=kb.nextInt();
Num n = new Num();
n.set(a,b);
n.add();
n.display();
}
}

RULE 1: within same package public and default will act as same and in
different package the default will act as private.

Accessing a class outside its package.

Rule 2: To import a class outside its package it must be declared as a public


class.

Rule 3: Making a class public does not automatically makes it method as public.
if we want to access any method outside its package then it must be declared
as public.

 we can place the above two file in different package .below is Num.java file
package packages.mymath2;

public class Num {


private int a,b,c;
public void set(int a,int b)
{
this.a=a;
this.b=b;
}
public void add()
{
c = a+b;
}
public void display()
{
System.out.println("nos are: "+a+" "+b);
System.out.println("their sum is: "+c);
}
}

below is UseNum.java file:

package packages.mymath;

import java.util.Scanner;
import packages.mymath2.Num;

public class UseNum {


public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.print("enter the num1: ");
int a = kb.nextInt();
System.out.print("enter the num2: ");
int b=kb.nextInt();
Num n = new Num();
n.set(a,b);
n.add();
n.display();
}
}

Rule 4: In java if a class is declared as public then the name of .java file must be
same as the name of public class

Rule 5: In java there can be only one public class in one.java file.it means that if
we have two public classes then they must be saved in their own .java files
and not in the single file.

Ques: Can we make class in java?

Ans: The answer to this question is both Yes and No.No for outer classes Yes
for inner classes.

Java permits us to make a class private only and only if the class is an inner
class. With outer classes we will not use the keyword private:

An outer class can be either default or public.


public class Outer
{
private class Inner
{

}
}
Java Accessibility Rules For Class Members
Access Modifier private public default protected
Place of Access
1) same class ✔️ ✔️ ✔️ ✔️
2) same


package
✔️ ✔️ ✔️
non sub
class


3) same
package, ✔️ ✔️ ✔️
sub class
4) different

❌ ❌ ❌
package
✔️
non sub
class
5) different

❌ ❌
package
✔️ ✔️
non sub
class
Collections
What is collection?
 A collection in java is a mechanism for storing group of objects as a single
entity as well as perform various operation on them.

 These operations can be adding new objects or searching an object or


updating an object or deleting an object or even sorting the objects.

 For example, suppose we are building an e-commerce application in java


then we can create a collection of Product objects, a collection of Customer
object, a collection of Vendors or even a collection of Order objects.

 But before we move further with collections, we might have a doubt that
why don’t we use arrays and why to learn Collections.

Drawbacks of Arrays.

1) At the time of declaration, we have to mention size of an array so


following is a syntax error in java: -
 Int [] arr = new int[]; // error
2) Arrays are of fixed size once created we can neither increase nor
decrease size of an array.
3) Like many other popular languages an array in java allows only
HOMOGENEOUS data.
4) No built-in support in the form of predefined method is available in java
for Arrays. Like there is no method in java for adding method in an array
or removing data.

Note : One Stop solution for all the above problems in java is the Collection
Framework.

Benefits of Collection
1) Collections do not require any size to be declare at the time of
declaration.
2) Collection are growable by nature. i.e at runtime they can resize
themselves as the need arises.
3) Collections allow us to store HETEROGENEOUS types of data in them,
although, it is not recommended.
4) Collections have very good built-in support by java in the form of
predefined methods for performing various operations on them like add(),
remove(), sort(), get() etc.
Array Collections
Fixed in size Growable in size
Only allows homogeneous data Allows homogeneous as well as
heterogeneous data
No support for predefined method Exhaustive support of predefined
method available for collections.
In java we can create array of Although collections only allows
premitive as well as objects objects to be store into them but we
can store primitive in a collections
because java will automatically
convert them into wrapper class
object while storing OR retrieving
them from collections.

int vs Integer
 data type  class

 value  object

 int a = 10;  Integer obj = new Integer(10);

 Or Integer obj = 10;

Types of Collection
There are three main types of Collections:

1. Lists: always ordered, may contain duplicates and can be handled the
same way as usual arrays.
2. Sets: cannot contain duplicates and provide random access to their
elements.
3. Maps: connect unique keys with values, provide random access to its
keys.

Important Methods of Collection


The Collection Interface is one of the root interfaces of the Java Collection classes. The general method list
of the Collection interface is:
1. boolean add(Object obj) // add an object to the collection
2. void clear() // clear the collection or empty the collection
3. boolean contains(Object obj) // return true if the collection contains the object
4. boolean equals(Object obj) // checks if
5. int hashCode() // we will study later after set
6. boolean isEmpty()
7. Iterator iterator() // we will study later after set
8. boolean remove(Object obj)
9. int size()

Collection vs Collections
 Collection in java is an interface available in the package
java.util and it acts as the super interface for all collection classes

 In java we have two entities called Collection and Collections


both related to the topic Collection Frameworks.

 Due to similarity in names, many beginners remain confused


about their use.

 Collection is an interface which is the root of the Collection


hierarchy and works as parent interface for numerous collection related classes.

 On the other hand Collections is a special class made available


by java team containing many helper methods like sort(), copy(),
binarySearch(), etc to perform various operations on Collections.

 Both of them (Collection and Collections) come from the package


java.util.

COLLECTION HIERARCHY

Collection

List Set Queue


Quiz Time
1. The core collection interfaces are organized into two distinct
inheritance trees. One interface in particular is not a part of
Collection, and therefore sits at the top of its own tree. What is
the name of this interface?

Answer: Map

2. What interface represents a collection that does not allow


duplicate elements?

Answer: Set

3. Which class forms the root of the collections hierarchy?


Answer: None

4. What interface forms the root of the collections hierarchy?


Answer: Collection
5. What interface represents an ordered collection that may
contain duplicate elements?
Answer: List
6. What interface represents a collection that holds elements to
be processed in FIFO order?
Answer: Queue
7. What is the difference between Collection and Collections ?
Answer: First is an interface while second is a class.

8. Difference between HashSet and TreeSet


Answer:

HashSet TreeSet
Maintains element in Maintains
Random Order element in sorted
order
Backed by HashMap Backed by Binary
tree
Faster Slower
Less Functionality Rich in
Functionality

9. In an e-commerce application which collection would


you use if you needed to maintain and search on orders
identified by their unique order-id?

answer: Map
The List Interface

 The java.util.List interface is a subtype of the


java.util.Collection interface and represents an ordered
collection (Sometimes called a sequence).
 It means we can access the elements of a list in a specific
order, and by an index too.
 It allows duplicate objects.
 Each element is inserted and accessed in the list using its
index.

Implementation Classes Of “List”


We can choose between the following List implementations
in the Java Collections API:

java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack

The ArrayList class


1. ArrayList implements the List interface.
2. ArrayList capacity grows automatically.
3. It allows duplicate elements.
4. Insertion order is preserved in the ArrayList.
5. ArrayList is created with an initial size of 10, although we can
change it’s initial capacity.

Ques: How ArrayList resizes itself?

1) By default the ArrayList has capacity of 10 and uptill 10


elements the capacity of the ArrayList remains same.
2) After the 10th element when we will add the 11th element
following actions will take placed:
a. A new Array of a new capacity gets created.
b. All 10 elements from the previous array along with the 11th
element are copied to the new Array.
c. The previous array is made available for the garbage
collector.
3) The formula for calculating the new capacity has changed from
time to time and is implementation dependent.
4) However in java7 the formula was:
a. new capacity = (old capacity*3/2) + 1.
5) From java8 onwards the formula has become:
a. new capacity = (old_capacity + old_capacity >> 1)

Creating The “ArrayList” Object


• ArrayList can be created in 2 ways:

Type UnSafe & Type Safe

Type UnSafe ArrayList


 Type UnSafe ArrayList can be created as shown below
ArrayList obj=new ArrayList( );
 Although they are easier to create but we cannot check
what kind of data we are adding in the ArrayList.
For ex:
 obj.add(“Amit”);
 obj.add(25);
 obj.add(true);

All the above lines will successfully compile and run.


## Why Java Does Not Recommend To Use Type UnSafe ArrayList ?

Answer:

This is because a type-unsafe ArrayList has 2 issues:

ArrayList obj=new ArrayList( );


obj.add(“Amit”);
obj.add(25);
obj.add(true);

1. While getting back the values from the ArrayList we


must be sure about the type of data it is holding, otherwise
code will give error:

int x=obj.get(0);// Syntax error

2. Since the get() method has the return type of Object we


must use proper type-conversion ( down casting) while
receiving the value:

String x=obj.get(0);// Syntax error


String x=(String)obj.get(0); // Correct

ArrayList Methods:
Inserting Elements in ArrayList
 To insert an element in the ArrayList. We have to call
the method add().

 This method has 2 versions:


 Prototypes:

o Public boolean add(Object);


 The first method accepts an Object as
argument and adds that Object at the end of
the ArrayList

o Public void add(int,Object);


 The second method accepts an index
number as well as an Object as argument
and adds the Object at the specified index
• If index is out of range then it throws the exception
IndexOutOfBoundsException

• For Ex:

 ArrayList <String> cities = new ArrayList<>();

 cities.add(“Bhopal”);

 cities.add(0, “Indore”);

Retrieving Elements Of ArrayList


To retrieve an element from the ArrayList , we have to call
the method get( )

Prototype:

public Object get(int index)


This method accepts an index number as argument and
returns the element at that position
If index is out of range then it throws the exception
IndexOutOfBoundsException

For Ex:

String s=cities.get(0);
String p=cities.get(1);
System.out.println(s); // will show Indore
System.out.println(p); // will show Bhopal

add() method:

A simple program for add method.

 package sca.collectioncodes;
 import java.util.ArrayList;
 import java.util.List;

 public class ArrayListEx1 {


 public static void main(String[] args) {
 ArrayList<String> monthsList = new
ArrayList<>();
 monthsList.add("january");
 monthsList.add("February");
 monthsList.add("march");
 monthsList.add(3,"April");
 System.out.println(monthsList);
 }
 }

run:

 [january, febuary, march, April]

 Looping over ArrayList


Java provides us numerous ways to traverse an
arraylist but three of them are very popular and they
are:

1)Regular for
2)For each (enhanced for)
3)Iterator

1. Traversing using Regular For:


import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class ArrayListEx3

public static void main(String[] args)

{
List<String> months = new
ArrayList<>();

System.out.println("Enter the months:");

System.out.println("Enter the size of array:


");

int size = new


Scanner(System.in).nextInt();

for(int i=0;i<=size;i++)

System.out.print("enter the " + i + "th


element: ");

months.add(new
Scanner(System.in).next());

for(int i=0;i<months.size();i++)

System.out.print("The "+i+"th element is:


");

System.out.println(months.get(i));

}
2. Traversing using foreach loop(enhanced for):
package sca.collectioncodes;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class ArrayListEx4 {

public static void main(String[] args) {

List<String> months;

months = new ArrayList<>();

System.out.println("Enter the months:");

System.out.println("Enter the size of


array: ");

int size = new


Scanner(System.in).nextInt();

for(int i=0;i<=size;i++)

System.out.print("enter the " + i + "th


element: ");

months.add(new
Scanner(System.in).next());

for(String month:months)

{
System.out.println(month);

}
Checking size of ArrayList
• Size of an ArrayList means total number of elements
currently present in it.
• To retrieve size of an ArrayList , we have a method called
size() whose protoype is:
• public int size( )

For Ex:

 int n = cities.size();

Searching An Element In ArrayList


Sometimes we need to check whether an element exists in
ArrayList or not.

For this purpose we can use contains () method of Java.


contains() method takes type of object defined in the ArrayList
creation and returns true if this list contains the specified element.
For Ex:
boolean found=cities.contains(“Bhopal”);

Another Way Of Searching An Element In ArrayList


We also can use indexOf() method of ArrayList in Java to find
out index of a particular object.

int index = cities.indexOf(“Bhopal”);


Exercise 2
 According to IMDB following are top earning Bollywood
movies of the year 2023, till now:
 1-Pathaan
 2-Gadar-2
 3-The Kerala Story
 4-Adipurush
 5-TJMM
 WAP to do the following:

1. Accept names of these 5 movies and store them in the


ArrayList
2. Now ask the user to input a movie name and search and
print it’s ranking. If the movie is not found then print the
message Movie not found

Solution:
1. package sca.collectioncodes;

2. import java.util.ArrayList;
3. import java.util.List;
4. import java.util.Scanner;

5. public class ArrayListEx5 {


6. public static void main(String[] args) {
7. Scanner kb = new Scanner(System.in);
8. List<String>movies = new ArrayList<>();
9. System.out.print("Enter the size of movie: ");
10. int size = kb.nextInt();
11. kb.nextLine();
12. for(int i=0;i<size;i++)
13. {
a. System.out.print("Enter the " + (i+1)+ "th movie: ");
b. String name = kb.nextLine();
c. name = name.toUpperCase();
d. movies.add(name);
14. }
15. System.out.print("Enter movie name to search: ");
16. String searchMovie = kb.nextLine();
17. searchMovie = searchMovie.toUpperCase();
18. int index = movies.indexOf(searchMovie);
19. if(index == -1)
20. {
a. System.out.println(searchMovie + " not found!");
21. }
22. else
23. {
a. System.out.println( searchMovie +" is found at index " + (index+1));
24. }
25. }
26. }

Removing an Item from ArrayList


• There are two ways to remove any element from ArrayList in
Java.
• The method to be called is remove( )
• This method has 2 versions:
• Prototype:
• public boolean remove(Object)
• public Object remove(int)
• We can either remove an element based on its index or by
providing object itself.

cities.remove(0);
cities.remove(“Indore”);

Exercise 3
• WAP to do the following
1. Accept names of 5 fruits from the user .
2. Then ask the user to input a fruit name and remove it from
the list .
3. Now print the modified list and if the fruit name is not found
then print the message Fruit not found
Solution:
Fruits.java file
package sca.arraylist.exercise2;

import java.util.Objects;

public class Fruits {

String fname;

String taste;

public String getFname() {

return fname;

public void setFname(String fname) {

this.fname = fname;

public String getTaste() {

return taste;

public void setTaste(String taste) {

this.taste = taste;

public Fruits(String fname, String taste) {


this.fname = fname;

this.taste = taste;

@Override

public int hashCode() {

int hash = 7;

hash = 89 * hash + Objects.hashCode(this.fname);

hash = 89 * hash + Objects.hashCode(this.taste);

return hash;

@Override

public boolean equals(Object obj) {

if (this == obj) {

return true;

if (obj == null) {

return false;

if (getClass() != obj.getClass()) {

return false;

final Fruits other = (Fruits) obj;

if (!Objects.equals(this.fname, other.fname)) {

return false;

}
if (!Objects.equals(this.taste, other.taste)) {

return false;

return true;

@Override

public String toString() {

return "Fruits{" + "fname=" + fname + ", taste=" +


taste + '}';

UseFruits.java file
package sca.arraylist.exercise2;

import java.util.ArrayList;

import java.util.List;

import java.util.Scanner;

public class UseFruit {

public static void main(String[] args) {

Scanner kb = new Scanner(System.in);

List<Fruits> fruits = new ArrayList<>();

System.out.print("enter the size: ");

int size = kb.nextInt();


for(int i=0;i<size;i++)

System.out.print("enter fruit name: ");

String name = kb.next();

System.out.print("enter fruit taste: ");

String taste = kb.next();

Fruits newFruit = new Fruits(name, taste);

fruits.add(newFruit);

System.out.println("all fruits are placed!");

// displaying all fruits

for(Fruits currentFruit:fruits)

System.out.println(currentFruit);

System.out.print("Enter fruit name and taste to


remove: ");

String dname = kb.next();

String dtaste = kb.next();

Fruits delete = new Fruits(dname, dtaste);

boolean result;

result = fruits.remove(delete);

if(result)

System.out.println("fruits deleted");

else
System.out.println("deletion failed");

for(Fruits currentFruit:fruits)

System.out.println(currentFruit);

Introduction To Custom ArrayList


• What is a custom ArrayList ?
• A custom ArrayList is an ArrayList which can hold
objects of programmer defined classes .
• For example , suppose we have a class called Emp
and we want to store Emp objects in the ArrayList .
Then such an ArrayList will be called custom
ArrayList

 How do we create a custom ArrayList ?


• To create a custom ArrayList , we use the following
syntax:
• List <name of our class> refName= new ArrayList<
>( );
• For ex:

• List<Emp> empList=new ArrayList<>();


 How do we add objects in a custom ArrayList ?
• To add objects of our class in a custom ArrayList , we
use the same syntax as before , i.e. by calling the
method add()

For ex:
List<Emp> empList=new ArrayList<>();
Emp e=new Emp(21, “Ravi”,50000.0);
Emp f=new Emp(25, “Sumit”, 40000.0);
empList.add(e);
empList.add(f);

Point To Remember
• If we are adding objects of our own class in
ArrayList , then we must always override the equals( )
method inherited from the super class Object.
• This is because whenever we will call the method
remove( ) on the ArrayList object , it internally calls
the equals( ) method of our class .
• This also happens when we call the methods
indexOf( ) or contains( )
How To Sort The ArrayList ?

o The Java language provides us predefined sorting

functions/methods to sort the elements of


collections like ArrayList.
o Thus we do not have to write our own logic for

sorting these collections.


o This is done using a class called “Collections” in

the package java.util which contains a static


method called sort( ) which can sort an ArrayList
o The prototype of the method is:

 public static void sort(List L)


o This method accepts a List as argument and sorts

it’s elements in natural order .

What Is Natural Order?

• Natural order means the default sorting order which is


as follows:
• If the List consists of String elements, it will be
sorted into alphabetical order.
• If it contains Integers , it will be sorted in numeric
order.
• If it consists of Date elements, it will be sorted into
chronological order.

Summary Of Benefits

1. Maintains the insertion order of elements


2. Can grow dynamically
3. Elements can be added or removed from a
particular location
4. Provides methods to manipulate stored
objects

The Linked List Class

• LinkedList implements the List interface.


• It Uses Doubly Linked List internally.
• No initial capacity
• Capacity/size increases as elements are added
• Insertion order is preserved
• Good choice when frequent operations are adding
and removing and worst when frequent operation is
retrieval

Internal Mechanism Of LinkedList


A LinkedList is an organized collection of elements
called as nodes where each node contains an item ,a
reference to the next element and a reference to the
previous element

Adding Elements In The LinkedList

List <String>cities = new LinkedList<String>();


cities.add(“Bhopal”);
cities.add(“Paris”);
cities.add(“Delhi”);
The above code will create three nodes having “Bhopal” ,
“Paris” and “Delhi” as their contents and references of
three nodes adjusted to point to previous and next nodes

“Bhopal” == ”Paris” == ”Delhi”


Now suppose we want to add “New York” at position 3 then
we would write
cities.add(2,”New York”);
To make this adjustment , three steps will be done:
a. Creating a new node with “New York”
b. Breaking links of “Paris” and “Delhi”
c. Adjust links of “Paris””NewYork” as well as
“NewYorkDelhi”
“Bhopal” == ”Paris” == ”NewYork” == ”Delhi”

Getting Element From The LinkedList


• To get a particular element from LinkedList we use the
same method called get( ) passing it the index no .
• Example
System.out.println(cities.get(1));// Paris

• Although LinkedList provides us a get( ) method , but


when we use it to access a particular element then it
internally traverses the complete list upto the element
required .
• On the other hand if we use ArrayList then directly the
element is accessed based on index no.
• Thus ArrayList supports Random Access , while Linked
List supports Sequential Access

Summary Of Benefits
1. Maintains the insertion order of elements
2. Efficient for adding and removing elements
from the middle of the list
3. Good for sequential access , but not for
random access

The Set Interface

1. The Set interface extends Collection


interface
2. A Set is a collection that cannot contain
duplicate elements.
3. A Set is NOT an ordered collection
4. Unlike List and arrays, Set does NOT
support indexes or positions of it’s elements.

Implementation Classes Of Set

There are 2 implementation classes of Set interface:


1- HashSet
2- TreeSet
The HashSet represents a set backed by a hash table
providing constant lookup−time access to unordered
elements.
The TreeSet maintains its elements in a sorted order
within a BST

The HashSet Class

1.This class implements the Set interface


2.It internally uses a hash table for storage and
applies a mechanism called hashing for storage and
retrieval of data
3.It makes no guarantee as to the iteration order of
the set

Inserting Elements In HashSet

• To insert an element in the HashSet , we have to call the


method add( )
• This method has following prototype:
• Prototype:
• public boolean add(Object)
• It accepts an Object as argument and adds that
Object in the HashSet . If adding is successful
it returns true otherwise it returns false.

• For Ex:
Set<String> HSet = new HashSet<String>();
HSet.add("C");
HSet.add("A");
HSet.add("B");

Exercise 5:
• WAP to store names of first four months in the HashSet
and them print them .

• Solution:
package sca.set;
import java.util.HashSet;
import java.util.Set;
public class HashSetEx1 {
public static void main(String[] args) {
Set <String> mySet = new HashSet<>();
System.out.println("Adding jan? "+
mySet.add("jan"));
System.out.println("Adding feb? "+
mySet.add("feb"));
System.out.println("Adding march? "+
mySet.add("march"));
System.out.println("Adding April? "+
mySet.add("April"));
System.out.println("Adding June? "+
mySet.add("June"));
System.out.println(mySet);
}
}

What is an Iterator ?

1.The List and Set collections provide iterators,


which are like pointers that allow going over all the
elements of a collection in sequence
2.To access a collection through an iterator, we
have to obtain the object of type Iterator which is
done by calling the method called iterator( ) ,
available in all Collection classes
3. The prototype of this method is:
public Iterator iterator( )
4.By using this Iterator object, we can access each
element in the collection, one element at a time

Methods Of Iterator

1. public boolean hasNext( ) : Checks whether there


is an element present in the Collection to be
accessed . If an element is present it returns true
otherwise it returns false
2. public Object next( ) : Moves the internal pointer to
the next position and returns the element present
there. If no element is present then it throws
NoSuchElementException

Working Of Iterator

Suppose we write the statement:


Iterator it = hs.iterator();
When the above statement runs , the internal
pointer of
the Iterator called Cursor starts pointing to the
position
which is before first element of the Collection.

Now , when we write the following code:


it.hasNext();
it.next();
the Cursor starts pointing to the FIRST element in the
Collection

If we again write the following code:


it.hasNext();
it.next();
the Cursor starts pointing to the SECOND element
in the
Collection

Repeating this process finally sends the Cursor to


the
LAST element of the Collection

After reading the final element, if we run code


it.hasNext()
then it returns “false” value.

Steps To Use Iterator

In general, to use an iterator to cycle through the


contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by
calling the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have
the loop iterate as long as hasNext( ) returns true.
3. Within the loop, obtain each element by calling
next( ).

Example:
Set <String> hs=new HashSet<String>();
hs.add("January");
hs.add("February");
hs.add("March");
hs.add("April");
Iterator it=hs.iterator();
while(it.hasNext())
{
String s=(String)it.next();
System.out.println(s);
}

A very Important Point

package sca.set;

import java.util.HashSet;

import java.util.Set;

public class HashSetEx3 {

public static void main(String[] args) {

Set<String> hs = new HashSet<String>();

hs.add("Amit");

hs.add("Sumit");
hs.add("Amit");

System.out.println(hs);

Output: [Amit, Sumit]

Now Again Guess The Output ?

class Student{
private String name;
public Student(String name){
this.name=name;
}
public String toString(){
return name;
}
}
class HashSetDemo{
public static void main(String[] args) {
Set <Student> hs;
hs=new HashSet<Student>();
Student s1=new Student("Amit");
Student s2=new Student("Sumit");
Student s3=new Student("Amit");
hs.add(s1);
hs.add(s2);
hs.add(s3);
System.out.println(hs);
}
}
Output:
[Amit , Sumit , Amit]

Why Duplicates Were Not Removed ?

• This is because when we add a new object to


HashSet , then java searches it in the hash table
using it’s hash code .
• And if no object is found with the matching hash code
then it inserts the new object in the HashSet
• Now this raises a question “ what is a hash code ?”
• The hash code of a Java object is simply an integer
allotted by the JVM to uniquely identify an object.
• To get the hash code of an object we can call the
method hashCode( ) which is inherited by every class
from the class Object
• But with respect to Collections , hash code should not be unique
for every object.
• As per Collections , if two objects are equals then these two
objects should return same hash code.
• So we have to override hashcode() method of a class in such way
that if two objects are equal, then those two objects must return
same hash code
• But , since we have not overridden hashCode( )
method in our Student class so we got two student
objects having the same name.
What Other Method We Should Override With hashCode( )?
 When we want to add our own object in ArrayList
then we must override following methods.
1) toString()
2) equals() // for proper working of
remove(),indexOf(), contains()
3) compareTo() // for proper working of sort()

 Similarly if we want to add our object to hash based


classes the we must override following:

• We should also override equals( ) alongwith hashCode( )


because the HashSet also calls equals( ) along-with hashCode( )
to match the actual value.
• This is called hashcode-equals contract in java

Exercise 7:

Write a program to implement a Library Management


System with the following features:

1. It should contains Books where each Book has a


name , an author and price.
2. All the books must be unique i.e. it should not accept
a Book if it is already present
3. Retrieval of Book should be as fast as possible

The program should have 3 classes:

1. Book : should contain 3 data members called name ,


author and price . Also provide appropriate
constructor and other important methods
2. Library: should contain a HashSet of Book . Also
provide 3 methods called addBook( ),
getBookCount() and getAllBooks( )
3. UseLibrary: This will be our driver class . It will
contain code to create 4 Book objects , add them to
the Library and display their details.

Solution:
1. Book class
package sca.set.librarymanagementsystem;

import java.util.Objects;

public class Book {

private String bookName;

private String authorName;

private double price;

public Book(String bookName, String


authorName, double price) {

this.bookName = bookName;

this.authorName = authorName;
this.price = price;

@Override

public int hashCode() {

int hash = 7;

hash = 53 * hash +
Objects.hashCode(this.bookName);

hash = 53 * hash +
Objects.hashCode(this.authorName);

hash = 53 * hash + (int)


(Double.doubleToLongBits(this.price) ^
(Double.doubleToLongBits(this.price) >>> 32));

return hash;

@Override

public boolean equals(Object obj) {

if (this == obj) {

return true;

if (obj == null) {

return false;

if (getClass() != obj.getClass()) {

return false;

}
final Book other = (Book) obj;

if (Double.doubleToLongBits(this.price) !=
Double.doubleToLongBits(other.price)) {

return false;

if (!Objects.equals(this.bookName,
other.bookName)) {

return false;

if (!Objects.equals(this.authorName,
other.authorName)) {

return false;

return true;

public String toString() {

return "Book{" + "bookName=" + bookName +


", authorName=" + authorName + ", price=" +
price + '}';

2) Library class:

package sca.set.librarymanagementsystem;
import java.util.HashSet;

import java.util.Set;

public class Library {

private Set<Book>bookSet;

public Library(){

bookSet = new HashSet<Book>();

public boolean addBook(Book b){

return bookSet.add(b);

public int getBookCount(){

return bookSet.size();

public Set<Book> getAllBooks(){

return bookSet;

3) UseLibrary class
package sca.set.librarymanagementsystem;

import java.util.Scanner;

import java.util.Set;

public class UseLibrary {

public static void main(String[] args) {

System.out.println("Welcome to Library Management


system");

Scanner kb = new Scanner(System.in);

Library lib = new Library();

while(true)

System.out.println("You can perform following


operations: ");

System.out.println("1) Add book");

System.out.println("2) See book count");

System.out.println("3) get all book");

System.out.println("0) enter 0 for exit!");

System.out.println("Enter you option: ");

int opt = kb.nextInt();

switch(opt)

case 1:

System.out.print("Enter book name: ");

kb.nextLine();
String bookName = kb.nextLine();

System.out.print("Enter author name: ");

String authName = kb.nextLine();

System.out.print("Enter book price: ");

double price = kb.nextDouble();

Book b = new
Book(bookName,authName,price);

boolean res = lib.addBook(b);

if(res)

System.out.println("Book added
successfully!");

else

System.out.println("Book was not added!!");

break;

case 2:

System.out.println("Total books present in


library: " + lib.getBookCount());

break;

case 3:

Set<Book> bookset = lib.getAllBooks();

for(Book book:bookset)

System.out.println(book);

}
break;

case 0:

System.out.println("program ended
successfully! visit again");

return;

default:

System.out.println("input mismatched! try


again");

break;

The TreeSet class


 This class implements the Set interface.
 The TreeSet class is useful when we need to extract
elements from a collection in a sorted manner.
 It stores its elements in a tree and they are
automatically arranged in a sorted order.
Program:
import java.util.*;
public class TreeSetDemo {
public static void main(String args[]) {
Set <String>ts = new TreeSet< >();
ts.add("C");
ts.add("A");
ts.add("B");
ts.add("E");
ts.add("F");
ts.add("D");
System.out.println(ts);
}
}
Output:
[A, B, C, D, E, F]

Traversing a TreeSet
import java.util.*;
public class SetDemo {
public static void main(String[] args) {
Set<String> st = new TreeSet<>();
st.add("Gyan");
st.add("Rohit");
st.add("Anand");
st.add("Arunesh");
Iterator itr = st.iterator();
while (itr.hasNext()) {
String str = (String) itr.next();
System.out.println(str);
}
}
}

Output:
Anand
Arunesh
Gyan
Rohit

Adding Custom Objects To TreeSet


• Suppose we want to create a TreeSet of Book object and we want
to get the output in ascending order of price
• Now , if we write :
• Set<Book> ts=new TreeSet<Book>( );
• Book b1=new Book("Let Us C","Kanetkar",350);
• Book b2=new Book("Java Certification","Kathy",650);
• Book b3=new Book("Mastering C++","Venugopal",500);
ts.add(b1);
• ts.add(b2);
• ts.add(b3);
• Then java will throw a ClassCastException.
Why Did This Happen ?
• This is because for any object which we add to the TreeSet
created using default constructor , then 2 conditions must be
compulsorily satisfied:
1. The objects added must be homogeneous
2. The objects must be comparable i.e. the class must
implement the java.lang.Comparable interface.
 In our case first condition is satisfied but since Book has
 not implemented the Comparable interface, a
 ClassCastException arised.
 So to solve the above exception , we must implement
 the Comparable interface in our Book class

Exercise 8:
Modify the Library Management System code by adding
one more feature which is to print Books in ascending
order of price . Also display the Books one by one
using iterator

Solution:
Book.java
package sca.set.treeset.assignment2;

public class Book implements Comparable<Book>{

private String bookName;

private String authorName;

private Double price;


public Book(String bookName, String
authorName, double price) {

this.bookName = bookName;

this.authorName = authorName;

this.price = price;

@Override

public String toString() {

return "Book{" + "bookName=" + bookName +


", authorName=" + authorName + ", price=" + price
+ '}';

@Override

public int compareTo(Book o) {

return this.price.compareTo(o.price);

UseBook.java:
public class UseBook {

public static void main(String[] args) {

TreeSet<Book> myBooks = new TreeSet<>();


Book b1 = new Book("Java Basics", "Aryan Gupta",
4000.35);

Book b2 = new Book("mastering c++",


"Sachin", 1000.5);
Book b3 = new Book("React js", "Aryan
Gupta", 9000);

Book b4 = new Book("JavaScript", "Harsh


Sharma", 2000.3);

myBooks.add(b1);

myBooks.add(b2);

myBooks.add(b3);

myBooks.add(b4);

for(Book b:myBooks){

System.out.println(b);

// printing using iterator

Iterator<Book> it = myBooks.iterator();

while(it.hasNext())

Book b = it.next();

System.out.println(b);

// printing highest price

System.out.println("costliest book is: " +


myBooks.last());

}
Some Extra Methods Of TreeSet
Since TreeSet implements NavigableSet and SortedSet interfaces
, it has some more methods as compared to HashSet. Some of it’s
very important methods are:
 public Object last( ) : Returns the last (highest) element currently in
this set.
 public Object first( ): Returns the first (lowest) element currently in
this set.
 public Object lower(Object) : Returns the greatest element in this set
strictly less than the given element, or null if there is no such element.
 public Object higher(Object) : Returns the least element in this set
strictly greater than the given element, or null if there is no such
element.

The Map Interface


 A Map is an object that always stores the data in
pairs called key-value pair.

• Although Map does not inherit Collection interface but has methods
similar to Collection
How values are stored in Map ?

1. A Map stores data in pairs called key-value pairs.

2. Each key-value pair saved as an object of type Entry.

3. Each Entry must have a unique keys in the Map

Important Methods of Map


1. Object put(Object k, Object v):

 Puts an Entry in the Map, overwriting any previous value associated


with the key.
 The key and value are k and v, respectively.
 Returns null if the key did not already exist , otherwise it returns the
previous value linked to the key

2. Object get(Object k):

 Returns the value associated with the key k


 If the key is not found , it returns null.

3. void clear( ):

 Removes all key/value pairs from the Map.

4. boolean containsKey(Object k):


 Returns true if the Map contains k as a key.
 Otherwise, returns false.
5. boolean containsValue(Object v):
 Returns true if the Map contains v as a value.
 Otherwise, returns false.
6. boolean isEmpty( ):

 Returns true if the Map is empty.


 Otherwise, returns false.
7. int size( ):
 Returns the number of key/value pairs in the Map.
8. Object remove(Object k):
 Removes the entry whose key equals k
 Returns the previous value associated with the specified key.
 Otherwise it returns null if there was no mapping for the key.

9. Collection values( ):
 Returns a Collection containing the values in the Map.
10. Set keySet( ):
 Returns a Set that contains all the keys stored in the Map.

11. Set entrySet( )


 Returns a Set that contains the entries in the Map.
 The Set contains objects of type Map.Entry.

Important Methods Of Entry

1. Object getKey( ):
 Returns the key corresponding to this Entry object
2. Object getValue( ):
 Returns the value corresponding to this Entry object

3. Object setValue(Object):
 Replaces the old value corresponding to this entry with the specified
value
 Returns the old value

Implementation Classes
The Collections Framework provides 2 very important Map
implementation:

1 - HashMap

2 - TreeMap

HashMap:

The HashMap is a class which is used to perform some


basic operations such as inserting, deleting, and
searching elements in a Map

TreeMap:

The TreeMap implementation is useful when we need


to traverse the keys from a collection in a sorted
manner. The elements added to a TreeMap must be
sortable in order to work properly.

The HashMap class

• Internally uses HashTable to store the data.


• Stores data as key-value pairs
• It contains only unique elements.
• It is not an ordered collection.
• It neither does any kind of sorting on the stored keys and
values.
• Ensures that the retrieval of the object will be in constant time i.e.
O(1)

Adding Data In HashMap


Map<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put(“Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);

Retrieving Data From HashMap


• Retrieval of data from HashMap can be done in 4 ways:
• Retrieving all elements together
• Retrieving only keys
• Retrieving only values
• Retrieving key-value pairs

Retrieving All Values Together


For this we simply have to pass the name of Map reference to the method
println()
Example:
Map<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put(“Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);
System.out.println(teamSca);
Output:
{Faizan=8982585147, Afroz=7992202926, Ankit=8962336876,
Sachin=9826086245}

Retrieving Only The Keys


For this we have to do 2 things:
1. Call the method keySet() which returns a Set of keys
of the HashMap
2. Use an Iterator over this Set
Example:
Map<String,Long> teamSca = new HashMap<>();
.......
Set<String> s=teamSca.keySet();
Iterator <String> it=s.iterator();
while(it.hasNext())
{
String key=it.next();
System.out.println(key);
}
Output:
Faizan
Afroz
Ankit
Sachin

Retrieving Only The Values


For this we have to do 2 things:
1. Call the method values() which returns a Collection
of values of the HashMap
2. Use an Iterator over this Collection
Example:
Map<String,Long> teamSca = new HashMap<>();
.......
Collection<Long>c=teamSca.values();
Iterator <Long> it=c.iterator();
while(it.hasNext())
{
Long value=it.next();
System.out.println(value);
}
Output:
8982585147
7992202926
8962336876
9826086245
Retrieving Key-Value Pairs
For this we have to do 2 things:
1. Call the method entrySet( ) which returns a Set of all the data
in the HashMap
2. Each element in this Set is an object of type Entry
3. Entry is an inner interface of Map and has 2 methods called
getKey() and getValue()
4. So we will have to get an Iterator over this Entry

Example:
Map<String,Long> teamSca = new HashMap<>();
.......
Set e=teamSca.entrySet();
Iterator it=e.iterator();
while(it.hasNext())
{
Map.Entry et=(Map.Entry)it.next();
System.out.println(et.getKey()+","+et.getValue());
}
Output:
Faizan,8982585147
Afroz,7992202926
Ankit,8962336876
Sachin,9826086245

Checking whether a value exists or not

To get the Value from HashMap object we use the method:


boolean containsValue(value)
This method returns true if Map contains the specified value
otherwise returns false.

Program :
import java.util.*;
public class HashMapDemo{
public static void main(String args[]) {
Map<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);

boolean bool = teamSca.containsKey(“Sachin");


System.out.println(“Does Sachin is exists in HashMap : "
+ bool);

}
}

Output:
Does Sachin is exists in HashMap : true

Using size( ) and remove( )


To get total number of elements in a HashMap we use the method:
public int size()
To remove a particular key from the HashMap we use the method:
public Object remove(key)
This method removes the specified entry from the HashMap whose
key is passed as argument and returns the deleted value
Program:
import java.util.*;
public class HashMapDemo {
public static void main(String args[]) {
Map<String,Long> teamSca = new HashMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put(“Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);
System.out.println("The size of HashMap is : " + hm.size());
hm.remove(“Afroz");
System.out.println("The size of HashMap after alteration is : "
+ hm.size());
}
}

Output:
The size of HashMap is : 4
The size of HashMap after alteration is : 3

The TreeMap class


• TreeMap class implements NavigableMap , SortedMap and Map
interfaces.
1. The TreeMap class implements the Map interface by using a
Binary Search Tree.
2. A TreeMap provides an efficient means of storing key/value
pairs in sorted order
3. Doesn’t store duplicates

Example:
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
Map<String,Long> teamSca = new TreeMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put(“Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);
System.out.println(teamSca);
}
}

Output:
{Afroz=7992202926, Ankit=8962336876 Faizan=8982585147,
Sachin=9826086245}

Example:
import java.util.*;
class TreeMapDemo {
public static void main(String args[]) {
Map<String,Long> teamSca = new TreeMap<>();
teamSca.put("Sachin", 9826086245L);
teamSca.put("Afroz",7992202926L );
teamSca.put(“Faizan", 8982585147L);
teamSca.put(“Ankit", 8962336876L);
Set e=teamSca.entrySet();
Iterator it=e.iterator();
while(it.hasNext())
{
Entry et=(Map.Entry)it.next();
System.out.println(et.getKey()+","+et.getValue());
}
}
}

Output:
Afroz,7992202926
Ankit,8962336876
Faizan,8982585147
Sachin,9826086245

Exercise 10:
A Bank maintains bank account of it’s customers in the
database.
When you visit the bank and tell your account
number to the teller , he fetches your account details.
1. Create a collection and maintain bank accounts in that.
2. There should be a single entry for one account number.
3. We should be able to fetch the account details when an account
number is supplied to the collection.
The program should have 3 classes:
1. Account : should contain 3 data members called accountNumber,
name and balance . Also provide appropriate constructor and other
important methods
2. Bank: should contain a HashMap of Account . Also provide 5
methods called :
addAccount( )
getAccount()
removeAccount()
getCount()
getAllAccounts( )

3 UseBank: This will be our driver class . It will contain code to do


the following:

Create 4 Account objects and add them to the Bank .


Display their details.
Now fetch the details of a particular account by passing it’s
account number
Remove an account by passing it’s account number
Display total number of Accounts

HashMap v/s TreeMap


 HashMap is useful when we need to access the Map without
considering how they are added to the Map (means, unordered
lookup of values using their keys).
 HashMap doesn’t allow duplicated entries.
 TreeMap stores the elements in a Binary Search Tree.
 TreeMap allows us to retrieve the elements in some sorted order .
 So we can say that TreeMap is slower than HashMap

 What is PreparedStatement?
Ans: PreparedStatement

You might also like