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

Collections

The document provides an overview of Java Collections, explaining what collections are, their advantages over arrays, and the various types such as Lists, Sets, and Maps. It details the Java Collections Framework, its interfaces, and classes, including how to create and manipulate ArrayLists and LinkedLists. Additionally, it discusses custom ArrayLists, sorting methods, and the importance of overriding the equals() method for user-defined classes.

Uploaded by

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

Collections

The document provides an overview of Java Collections, explaining what collections are, their advantages over arrays, and the various types such as Lists, Sets, and Maps. It details the Java Collections Framework, its interfaces, and classes, including how to create and manipulate ArrayLists and LinkedLists. Additionally, it discusses custom ArrayLists, sorting methods, and the importance of overriding the equals() method for user-defined classes.

Uploaded by

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

COLLECTIONS

(An easy way to manage


Objects)
What Is A Collection ?
As the name indicates,a collection is a group of objects
known as its elements. Examples of collections are :
1. List of email ids
2. List Of Names
3. List of phone numbers
4. Records Of Students
5. Records of books . etc
How Java supports Collections ?
To handle such collection of objects, Java offers us a huge
set of predefined classes and interfaces called as
“The Collections Framework”

which is available in the package “java.util”


Why do we need to learn Collection
?
The first question which comes in mind of every programmer is
Why should I use Collection classes when I have an array ?
Answer:
Although arrays are very useful data storage structures but they
suffer from several important drawbacks which are:
1.Size needs to be declared at the time of declaration, so can
only be used if we know beforehand how many elements we
would be storing
2.Remains of fixed size
3.No ready made methods for performing operations like
inserting , removing , searching or sorting
4. Arrays are not based on any popular Data Structure
5. Can only hold homogeneous data elements
Advantages Of Collections

1. Can dynamically grow or shrink

1. Reduces programming effort

1. Increases program speed and quality

1. Provide predefined methods to perform all


operations
Arrays V/s Collections
Array Collections
Arrays are fixed in size , so once we Collections are growable by nature so
have created the array we can not after creation we can increase or
increase or decrease it’s size decrease their size

Arrays can hold primitives as well as Collections don’t work with primitives ,
objects they only can hold objects

Arrays can hold only homogeneous Collections can hold both


data homogeneous as well as heterogeneous
data

Good performance but poor memory Poor performance but good memory
utilization utilization

Coding is complex Coding is easy


Types Of Collections
There are 3 main types of collections:

• Lists: always ordered, may contain duplicates and can be


handled the same way as usual arrays
• Sets: cannot contain duplicates and provide random
access to their elements
• Maps: connect unique keys with values, provide random
access to its keys
The Collection Hierarchy
Important Methods Of Collections
The Collection interface is one of the root interfaces of the
Java collection classes. The general methods list of the
collection interface is:
1. boolean add(Object obj)
2. void clear( )
3. boolean contains(Object obj)
4. boolean equals(Object obj)
5. int hashCode( )
6. boolean isEmpty( )
7. Iterator iterator( )
8. boolean remove(Object obj)
9. int size( )
Collection V/s Collections
• For beginners there is a point of confusion regarding the
terms Collection and Collections

• Collection in java is an interface available in the package


java.util and it acts as the super interface for all collection
classes like ArrayList , LinkedList , HashSet etc

• Collections is a class in the package java.util which


contains various static methods for performing utility
operations on collection classes .

• Some of it’s popular methods are sort( ),copy( ),


binarySearch( ) etc
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


it’s 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

1. ArrayList capacity grows automatically.

1. It allows duplicate elements

1. Insertion order is preserved in the ArrayList

1. ArrayList is created with an initial size of 10 , although


we can change it’s initial capacity
Creating The “ArrayList” Object
• ArrayList can be created in 2 ways:

• Type UnSafe

AND

• 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.


Type Safe ArrayList
• Type Safe ArrayList can be created as shown below

ArrayList<String> obj=new ArrayList<String>( );

• The < > is called diamond operator in Java and was introduced from Java
7 onwards .

• It tells the compiler to only allow programmer to add String values in the
ArrayList.

• Any other type of value cannot be added in the ArrayList and if we try to
do so , the compiler will generate syntax error

• For ex:
obj.add(“Amit”); // Correct
obj.add(25); // Wrong
obj.add(true); // Wrong
Inserting Elements In ArrayList
• To insert an element in the ArrayList , we have to call the
method add( )

• This method has 2 versions:

• Prototype:

• public boolean add(Object)


• public void add(int , Object)

• The first method accepts an Object as argument and adds


that Object at the end of the ArrayList
Inserting Elements In ArrayList
• 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
Retrieving Elements Of ArrayList
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
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();
import java.util.*;

public class ArrayListExample1{

public static void main(String args[]){

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

list.add("Mango");//Adding object in arraylist

list.add("Apple");

list.add("Banana");

list.add("Grapes");

//Printing the arraylist object

System.out.println(list);

} }
Exercise 1
• WAP to store names of first four months in the ArrayList
and print them back .
Retrieving Item From ArrayList Using
Enhanced for
We can traverse an ArrayList also using enhanced
for loop

Using Enhanced For loop

for(String item: cities){


System.out.println("retrieved element: " + item);
}
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
• The WHO CoronaMeter , lists following 5 countries
worstly effected by COVID-19 .
• 1-America
2-India
3-Brazil
4-Russia
5-Columbia
WAP to do the following:
1. Accept names of these 5 countries and store them in
the ArrayList
2. Now ask the user to input a country name and search
and print it’s ranking. If the country name is not found
then print the message Country not found
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 .

1. Then ask the user to input a fruit name and remove it


from the list .

1. Now print the modified list and if the fruit name is not
found then print the message Fruit not found
COLLECTIONS
(An easy way to manage
Objects)
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.


Creating A Custom ArrayList
• How do we create a custom ArrayList ?

• To create a custom ArrayList , we use the following


syntax:
• ArrayList <name of our class> refName= new ArrayList< >( );

• For ex:
• ArrayList<Emp> empList=new ArrayList<>();
Creating A Custom 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:
ArrayList<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);
Exercise 4
Create a class called Emp with following instance
members:
1. age
2. name
3. sal

Provide appropriate constructor to initialize Emp object.


Then create a driver class called UseEmp which
maintains a list of employees . Now do the following
operations on this list:
1. Add 4 Emp objects
2. Display Emp records
3. Remove an Emp object from the list
4. Sort the List
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( )
Point To Remember
• Now if we do not override this method in our class then
the equals() method of Object class will get called and as
we know the equals () method of Object class compares
memory addresses of 2 objects .

• So even if objects are having same data member values


then also equals() method of Object class will return
false

• Thus the methods remove( ) , indexOf( ) and contains( )


will fail to find our object in the list.
How To Sort The ArrayList ?
• The Java language provides us predefined sorting
functions/methods to sort the elements of collections like
ArrayList.

• Thus we do not have to write our own logic for sorting


these collections.
How To Sort The ArrayList ?
• 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

• The prototype of the method is:


• public static void sort(List L)

• 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.
Example
ArrayList<String> months=new ArrayList<>();
ArrayList<Integer> days=new ArrayList<>();
months.add("January");
months.add("February");
months.add("March");
months.add("April");
days.add(31);
days.add(28);
days.add(31);
days.add(30);
Example
System.out.println("Before sorting:");
System.out.println(months);
Collections.sort(months);
System.out.println("After sorting:");
System.out.println(months);
System.out.println("Before sorting:");
System.out.println(days);
Collections.sort(days);
System.out.println("After sorting:");
System.out.println(days);
Output
Before sorting:
[January, February, March, April]
After sorting:
[April, February, January, March]

Before sorting:
[31, 28, 31, 30]
After sorting:
[28, 30, 31, 31]
How To Sort Custom ArrayList ?
• But when we call the sort( ) method of Collections class
and pass it our Emp list then it will generate an error.

• Can you guess why ?

• This is because we have not defined any sorting order for


our Emp objects !!!
Solution
• To solve this problem we will have to supply the
information to Collections class about how to sort the
Emp list.

• This is done by implementing an interface called


Comparable and overriding it’s method called
compareTo( ) which has the following prototype:

• public int compareTo(Object)


Summary Of Benefits
1. Maintains the insertion order of elements

1. Can grow dynamically

1. Elements can be added or removed from a particular


location

1. Provides methods to manipulate stored objects


COLLECTIONS
(An easy way to manage
Objects)
The “LinkedList” 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
LinkedList <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”
Adding Elements In The LinkedList
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
Getting Element From The LinkedList
•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

1. Efficient for adding and removing elements from the


middle of the list

1. Good for sequential access , but not for random access


The Set Interface
1. The Set interface extends Collection interface

1. A Set is a collection that cannot contain duplicate


elements.

1. A Set is NOT an ordered collection

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


Inserting Elements In HashSet
• 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:

HashSet<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 .
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
What is an Iterator ?
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

1. 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.
Working Of Iterator
Now , when we write the following code:
it.hasNext();
it.next();
the Cursor starts pointing to the FIRST element in the
Collection
Working Of Iterator
If we again write the following code:
it.hasNext();
it.next();
the Cursor starts pointing to the SECOND element in the
Collection
Working Of Iterator
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( )

1. Set up a loop that makes a call to hasNext( ). Have the


loop iterate as long as hasNext( ) returns true.

1. Within the loop, obtain each element by calling next( ).


Example
HashSet <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);
}
Exercise 6
Modify the ArrayList program and traverse the ArrayList
using iterator
A Very Important Point !
import java.util.*;
public class HashsetDemo {
public static void main(String[] args) {
HashSet <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 class HashSetDemo{
{ public static void main(String[] args) {
private String name; HashSet <Student> hs;
public Student(String name) hs=new HashSet<Student>();
Student s1=new Student("Amit");
{
Student s2=new Student("Sumit");
this.name=name; Student s3=new Student("Amit");
} hs.add(s1);
hs.add(s2);
public String toString() hs.add(s3);
{ System.out.println(hs);
return name; }
} }
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
Why Duplicates Were Not Removed
?
• 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
Why Duplicates Were Not Removed
?
• 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( )?
• 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.

1. All the books must be unique i.e. it should not accept a


Book if it is already present

1. Retrieval of Book should be as fast as possible


Exercise 7
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

1. Library: should contain a HashSet of Book . Also


provide 3 methods called addBook( ), getBookCount()
and getAllBooks( )

1. 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.
The TreeSet class
1. This class implements the Set interface.

1. The TreeSet class is useful when we need to extract


elements from a collection in a sorted manner.

1. 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[]) {
TreeSet <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) {
TreeSet<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 :
TreeSet<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
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:

1. public Object last( ) : Returns the last (highest)


element currently in this set.
2. public Object first( ): Returns the first (lowest) element
currently in this set.
3. 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.
4. 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.
HashSet v/s TreeSet
1.HashSet is much faster than TreeSet as it has a
constant-time for most operations like add, remove and
contains but offers no ordering guarantees like TreeSet.

2. TreeSet offers a few handy methods to deal with the


ordered set like first(), last(), etc which are not present in
HashSet

You might also like