Collections
Collections
Collections
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).
Import ---------------------------
Import ---------------------------
class <class_name>
-------------;
-------------;
}
Creating two classes in the same package
package mymath;
import java.util.Scanner;
RULE 1: within same package public and default will act as same and in
different package the default will act as private.
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;
package packages.mymath;
import java.util.Scanner;
import packages.mymath2.Num;
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.
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:
}
}
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.
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.
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
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.
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
COLLECTION HIERARCHY
Collection
Answer: Map
Answer: Set
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
answer: Map
The List Interface
java.util.ArrayList
java.util.LinkedList
java.util.Vector
java.util.Stack
Answer:
ArrayList Methods:
Inserting Elements in ArrayList
To insert an element in the ArrayList. We have to call
the method add().
• For Ex:
cities.add(“Bhopal”);
cities.add(0, “Indore”);
Prototype:
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:
package sca.collectioncodes;
import java.util.ArrayList;
import java.util.List;
run:
1)Regular for
2)For each (enhanced for)
3)Iterator
import java.util.List;
import java.util.Scanner;
{
List<String> months = new
ArrayList<>();
for(int i=0;i<=size;i++)
months.add(new
Scanner(System.in).next());
for(int i=0;i<months.size();i++)
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;
List<String> months;
for(int i=0;i<=size;i++)
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();
Solution:
1. package sca.collectioncodes;
2. import java.util.ArrayList;
3. import java.util.List;
4. import java.util.Scanner;
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;
String fname;
String taste;
return fname;
this.fname = fname;
return taste;
this.taste = taste;
this.taste = taste;
@Override
int hash = 7;
return hash;
@Override
if (this == obj) {
return true;
if (obj == null) {
return false;
if (getClass() != obj.getClass()) {
return false;
if (!Objects.equals(this.fname, other.fname)) {
return false;
}
if (!Objects.equals(this.taste, other.taste)) {
return false;
return true;
@Override
UseFruits.java file
package sca.arraylist.exercise2;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
fruits.add(newFruit);
for(Fruits currentFruit:fruits)
System.out.println(currentFruit);
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);
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 ?
Summary Of Benefits
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
• 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 ?
Methods Of Iterator
Working Of Iterator
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);
}
package sca.set;
import java.util.HashSet;
import java.util.Set;
hs.add("Amit");
hs.add("Sumit");
hs.add("Amit");
System.out.println(hs);
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]
Exercise 7:
Solution:
1. Book class
package sca.set.librarymanagementsystem;
import java.util.Objects;
this.bookName = bookName;
this.authorName = authorName;
this.price = price;
@Override
int hash = 7;
hash = 53 * hash +
Objects.hashCode(this.bookName);
hash = 53 * hash +
Objects.hashCode(this.authorName);
return hash;
@Override
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;
2) Library class:
package sca.set.librarymanagementsystem;
import java.util.HashSet;
import java.util.Set;
private Set<Book>bookSet;
public Library(){
return bookSet.add(b);
return bookSet.size();
return bookSet;
3) UseLibrary class
package sca.set.librarymanagementsystem;
import java.util.Scanner;
import java.util.Set;
while(true)
switch(opt)
case 1:
kb.nextLine();
String bookName = kb.nextLine();
Book b = new
Book(bookName,authName,price);
if(res)
System.out.println("Book added
successfully!");
else
break;
case 2:
break;
case 3:
for(Book book:bookset)
System.out.println(book);
}
break;
case 0:
System.out.println("program ended
successfully! visit again");
return;
default:
break;
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
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;
this.bookName = bookName;
this.authorName = authorName;
this.price = price;
@Override
@Override
return this.price.compareTo(o.price);
UseBook.java:
public class UseBook {
myBooks.add(b1);
myBooks.add(b2);
myBooks.add(b3);
myBooks.add(b4);
for(Book b:myBooks){
System.out.println(b);
Iterator<Book> it = myBooks.iterator();
while(it.hasNext())
Book b = it.next();
System.out.println(b);
}
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.
• Although Map does not inherit Collection interface but has methods
similar to Collection
How values are stored in Map ?
3. void clear( ):
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.
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:
TreeMap:
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
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);
}
}
Output:
Does Sachin is exists in HashMap : true
Output:
The size of HashMap is : 4
The size of HashMap after alteration is : 3
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( )
What is PreparedStatement?
Ans: PreparedStatement