0% found this document useful (0 votes)
17 views31 pages

Ch1 Collections

The document provides an overview of Java Collections, detailing how to use arrays to store objects and the limitations of arrays. It introduces the Collection Framework, which offers a unified architecture for managing groups of objects, including various interfaces and classes such as List, Set, and Map. Additionally, it includes example programs demonstrating the use of ArrayList and LinkedList for storing and manipulating data.
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)
17 views31 pages

Ch1 Collections

The document provides an overview of Java Collections, detailing how to use arrays to store objects and the limitations of arrays. It introduces the Collection Framework, which offers a unified architecture for managing groups of objects, including various interfaces and classes such as List, Set, and Map. Additionally, it includes example programs demonstrating the use of ArrayList and LinkedList for storing and manipulating data.
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/ 31

Unit 1 : COLLECTIONS

We use an array to store a group of elements. It is also possible to use an array to store a group of objects.
Using Array to store a group of objects:
Q. Write a Program to store a group of employee objects into an array retrieve the object data and
display
import java.io.*;

class Employee
{
int id;
String ename;

Employee(int i, String en)


{
id=i;
ename=en;
}

void display()
{
System.out.println("ID:" +id + "\t"+" NAME:"+ename);
}

class EmpGroup
{
public static void main(String [] args) throws IOException
{
BufferedReader br= new BufferedReader (new InputStreamReader(System.in));
Employee arr[]=new Employee[5];
for(int i=0; i<5; i++)
{
System.out.println("Enter ID:");
int id=Integer.parseInt(br.readLine());
System.out.println("Enter Name:");
String ename=br.readLine();
arr[i]=new Employee(id,ename);
}
System.out.println("Employee Data is:");
for(int i=0;i<arr.length;i++)
arr[i].display();
}
}
Inconveniences of using array mechanism:
- Arrays cannot grow dynamically.
- It is not possible to store different class objects into the same array.
- Adding objects at the end of array is easy, but insertion and deletion of elements in middle of
array is difficult.
- Retrieving elements from array is easy, if we want to process the data, then there is no methods
available

To overcome these issues alternative mechanism is required to store group of objects:


- The alternative is using an object to store a group of other objects.
- It means we can use a class object as an array. Such an object is called ‘Collection Object’ or
‘Container Object’.

Collection Objects:
- A Collection object or a container object is an object which can store a group of other objects.
- A collection object has a class called as ‘collection class’ or ‘container class’.
- All collection classes are available in the package java.util.
- A group of collection classes is called a ‘collection framework’.
Collection Framework:
- A collection framework is a class library to handle groups of objects. Collection framework
is implemented in java.util package.
- The Collection Frameworkin Java provides an architecture to store and manipulate the group of
objects.
- Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
- Java Collection means a single unit of objects.
- Collections are growable in nature. i.e., based on run time requirement we can store any number
of elements.
- Collections can hold both homogeneous and heterogeneous data elements.
- We can transfer the data from one method to another of any type and any number of elements.
- Collection object does not store the physical copies of other objects. JVM stores the references of
other objects into a collection object.
- A collections framework is a unified architecture for representing and manipulating collections.
- Collection Framework in Java supports two types of containers:
 One for storing a collection of elements (objects), that is simply called a Collection.
 The other, for storing key/value pairs, which is called a map. Maps store key/value pairs.
Although maps are not collections in the proper use of the term, but they are fully integrated with collections .
- Java Collection framework provides many interfaces (Set, List, Queue, Map) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet,
HashTable, HashMap, LinkedHashMap, TreeMap).

If our requirement is representing group individual objects as a single entity then the better option
is ‘Collection Framework’.

Collection Framework Hierarchy in Java:


- Collection Framework consists of four core interfaces such as Collection, List, Set, Map, and
two specialized interfaces named SortedSet and SortedMap for sorting.
- All collections frameworks contains
 Interfaces: These are abstract data types that represent collections. Interfaces allow
collections to be manipulated independently of the details of their representation. In
object-oriented languages, interfaces generally form a hierarchy.
 Implementations: These are the concrete implementations of the collection
interfaces. In essence, they are reusable data structures.
 Algorithms: These are the methods that perform useful computations, such as
searching and sorting, on objects that implement collection interfaces. The algorithms
are said to be polymorphic: that is, the same method can be used on many different
implementations of the appropriate collection interface.
Interfaces
- Collection: It is at the top of collection hierarchy and must be implemented by any class that
defines a collection. Following are some of the commonly used methods in this interface.

No. Method Description


1 public boolean add(E e) It is used to insert an element in this collection.
2 Public boolean addAll (Collection c) It is used to insert the specified collection
elements in the invoking collection.
3 public boolean remove(Object element) It is used to delete an element from the
collection.
4 public boolean removeAll(Collection c) It is used to delete all the elements of the
specified collection from the invoking
collection.
5 public boolean contains(Object element) It is used to search an element.
6 public boolean isEmpty() Returns true if collection is empty, else returns
false.
7 public int size() It returns the total number of elements in the
collection.
8 public void clear() It removes the total number of elements from
the collection.
9 public Object[] toArray() It converts collection into array.
10 public boolean retainAll(Collection c) It is used to delete all the elements of invoking
collection except the specified collection.
11 Iterator iterator() Returns an iterator for the invoking collection.
12 public boolean equals(Object obj) Returns true if the invoking collection and obj
are equal. Otherwise, returns false.
13 public boolean containsAll(Collection c) It is used to search the specified collection in
the collection.
14 public Iterator iterator() It returns an iterator.
15 public Object[] toArray(Object array[]) Returns an array containing only those
collection elements whose type matches of the
specified array

-
-
-
-
-
-
- List Interface:
 List(I) is a child interface of Collection.
 Here duplicates are allowed and insertion order is preserved
 Implemented class of List are : ArrayList, LinkList, Vector
 Apart from methods of Collection Interface, it adds following methods of its own
Methods Description
Object get( int index ) Returns object stored at the specified index
Object set( int index, E obj) Stores object at the specified index in the calling
collection
int indexOf( Object obj ) Returns index of first occurrence of obj in the collection
int lastIndexOf( Object obj ) Returns index of last occurrence of obj in the collection
List subList( int start, int end Returns a list containing elements between start and end
) index in the collection

- The Set Interface


 Set(I) is a child interface of Collection.
 This interface defines a Set.
 It extends Collection interface and doesn't allow insertion of duplicate elements.
 Implemented class of Set are HashSet, LinkedHashSet, TreeSet.
 Duplicates are not allowed and insertion order is not preserved.
 It doesn't define any method of its own.
 It has two sub interfaces, SortedSet and NavigableSet.
- SortedSet Interface
 SortedSet interface extends Set interface and arranges added elements in an ascending
order.
 SortedSet(I) is a child interface of Set.
 Implemented class of Set are TreeSet
 Duplicates are not allowed but all objects should be inserted according to some sorting
order.
- Queue Interface
 It extends collection interface and defines behavior of queue, that is first-in,first- out.
 Queue(I) is a child interface of Collection.
 Methods :
Methods Description
Object poll() removes element at the head of the queue and returns null if
queue is empty
Object remove() removes element at the head of the queue and throws
NoSuchElementException if queue is empty
Object peek() returns the element at the head of the queue without removing it.
Returns null if queue is empty
Object element() same as peek(), but throws NoSuchElementException if queue is
empty
booleanoffer( E obj ) Adds object to queue.
- Map Interface
 Not child interface of Collection.
 Map and Collection both are different
 A Map stores data in key and value pair.

- SortedMap Interface
 It is a child interface of map.
 If we want to represent a group of key value pairs according to some sorting order of
keys then should go for SortedMap

Implementations:

List Implementations: Lists are further classified into the following: ArrayList, LinkedList, Vectors

1. ArrayList class
 The ArrayList class implements the List interface.
 It uses a dynamic array to store the duplicate element of different data types.
 The ArrayList class maintains the insertion order and is non-synchronized.
 The elements stored in the ArrayList class can be randomly accessed
 Important points to note
 Underlying data structure for ArrayList is Resizable Array.
 Duplicates are allowed.
 Insertion order is preserved.
 Heterogeneous objects insertion is allowed.
 ‘Null’ insertion is possible.
 ArrayList is best choice if our frequent operation is retrieval.
 ArrayList is worst choice if our frequent operation is insertion or deletion in middle
 ArrayList is implemented as an ordinary array.
 Methods of ArrayList
Method Description
void add(Object element) It is used to insert the specified element at the last
position in a list.
void add(int index, Object element) It is used to insert the specified element at the specified
position in a list.
boolean addAll(int index, Collection c) It is used to append all the elements in the specified
collection, starting at the specified position of the list.
void clear() It is used to remove all of the elements from this list.
void ensureCapacity (int requiredCapacity) It is used to enhance the capacity of an ArrayList
instance.
E get(int index) It is used to fetch the element from the particular
position of the list.
boolean isEmpty() It returns true if the list is empty, otherwise false.
boolean contains(Object o) It returns true if the list contains the specified element
boolean remove(Object o) It is used to remove the first occurrence of the specified
element.
boolean removeAll(Collection c) It is used to remove all the elements from the list.
void replaceAll(Collection c) It is used to replace all the elements from the list with
the specified element.
void retainAll(Collection c) It is used to retain all the elements in the list that are
present in the specified collection.
int size() It is used to return the number of elements present in the
list.

/* Program to demonstrate ArrayList*/


import java.util.ArrayList;
class ArrayListDemo
{
public static void main(String[] args)
{
// creating an Array List named colors
ArrayList Al = new ArrayList();

// add elements in the Array List


Al.add("Red");
Al.add(5);
Al.add("Null");
Al.add("Orange");
Al.add("Red");

// printing the ArrayList


System.out.println(Al);
}
}
Constructor Summary
Constructor and Description
2. ArrayList(): Constructs an empty list with an initial capacity of ten.
ArrayList AL =new ArrayList();
ArrayList <E> AL =new ArrayList<E>();
//Once it reached to max capcity ArrayList will create new List having capacity as:
new_capatity=(current_capcity*3/2)+1
3. ArrayList(Collection<? extends E> c): Constructs a list containing the elements of the
specified collection, in the order they are returned by the collection's iterator.
ArrayList AL =new ArrayList(C);
4. ArrayList(int initialCapacity): Constructs an empty list with the specified initial capacity.
ArrayList AL =new ArrayList(1000);

PROGRAM: Write a java program to accept names of ‘n’ cities, insert same into array list collection and
display the contents of same array list, also remove all these elements.
/* Write a java program to accept names of ‘n’ cities, insert same into array list collection and display the
contents of same array list, also remove all these elements.*/
import java.util.ArrayList;
import java.io.*;
import java.util.ListIterator;

class ArrayListSetA1
{
public static void main(String[] args)throws IOException
{
int n;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// creating an Array List named cities
ArrayList cities = new ArrayList();//ArrayList <String> cities = new ArrayList<String>();
// add n city elements in the Array List

System.out.println("How many cities you want to enter?");


n=Integer.parseInt(br.readLine());
for(int i=0 ; i<n;i++)
{
System.out.println("Enter City Name: ");
cities.add(br.readLine());
}

System.out.println("List of cities :");


System.out.println(cities);

// Create ListIterator and iterate entries in it


ListIterator li = cities.listIterator();
System.out.println("List of cities using Iterator :");
while (li.hasNext())
System.out.println("From ListIterator = " + li.next());

//removing all cities


cities.clear();
System.out.println("List of cities after removal:");
System.out.println(cities);
}
}
5. Linked List :
 Java LinkedList class provides implementation of linked-list data structure. Important points
to note It uses doubly linked list to store the elements.
 Duplicates are allowed.
 Insertion order is preserved.
 Heterogeneous objects insertion allowed.
 ‘Null’ insertion is possible.
 LinkList is best choice if our frequent operation is insertion or deletion in middle.
 LinkList is worst choice if our frequent operation is retrieval operation.
 Methods of Java LinkedList
Method Description
void add(int index, Object It is used to insert the specified element at the specified position
element) index in a list.
boolean addAll(Collection c) It is used to append all of the elements in the specified collection to
the end of this list, in the order that they are returned by the
specified collection's iterator.
void addFirst(Object element) It is used to insert the given element at the beginning of a list.
void addLast(Object element) It is used to append the given element to the end of a list.
void clear() It is used to remove all the elements from a list.
boolean contains(Object o) It is used to return true if a list contains a specified element.
Object element() It is used to retrieve the first element of a list.
Object get(int index) It is used to return the element at the specified position in a list.
Object peek() It retrieves the first element of a list
void push(Object e) It pushes an element onto the stack represented by a list.
Object remove() It is used to retrieve and removes the first element of a list.
Object remove(int index) It is used to remove the element at the specified position in a list.
Object removeFirst() Removes the first element of a list
Object removeLast() removes the last element of a list
int size() It is used to return the number of elements in a list
Object getFirst()
Object getLast()
Constructor Summary
Constructor and Description
6. LinkedList(): Constructs an empty list.
LinkedList L1 = new LinkedList();
LinkedLst <E> L1 = new LinkedList<E>();
7. LinkedList(Collection<? extends E> c): Constructs a list containing the elements of the
specified collection, in the order they are returned by the collection's iterator.
LinkedList L1 = new LinkedList(C);

/* Program to demonstrate LinkedList */


import java.util.*;
public class LinkedListDemo{
public static void main(String args[]){
LinkedList<String> L1=new LinkedList<String>();
L1.add("Ravi");
L1.add("Vijay");
L1.add("Ravi");
L1.add("Ajay");
System.out.println(L1);

System.out.println("Using Iterator:");
Iterator<String>itr=L1.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}
}
}
NOTE: ArrayList, vector classes implements RandomAccess interface but LinkedList does not
implements it.

PROGRAM: Write a java program to read ‘n’ names of your friends, store it into linked list, also display
contents of the same.

/* Write a java program to read ‘n’ names of your friends, store it into linked list, also display
contents of the same. */

import java.util.*;
import java.io.*;
public class LinkedListSetA2{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int n;
LinkedList<String> friends=new LinkedList<String>();

System.out.println("How many friend names you want to enter?");


n=Integer.parseInt(br.readLine());

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


{
System.out.println("Enter Friend Name: ");
friends.add(br.readLine());
}

System.out.println("List of Friends :");


System.out.println(friends);

// Create ListIterator and iterate entries in it


ListIterator li= friends.listIterator();//You can also use Iterator li= friends.iterator();
System.out.println("List of cities using Iterator :");
while (li.hasNext())
System.out.println(li.next());
System.out.println(“USING forloop”)
for( String obj : friends)
System.out.println(obj)
}

}
 Vector:
 Vector implements a dynamic array which means it can grow or shrink as required. Like an
array, it contains components that can be accessed using an integer index.
 The Vector class implements a growable array of objects.

Constructor Summary
Constructor and Description
 Vector() : Constructs an empty vector so that its internal data array has size 10 and its standard
capacity increment is zero.
Vector V1=new Vector(); OR Vetctor <E> V2=new Vector<E>();
 Vector(Collection<? extends E> c): Constructs a vector containing the elements of the specified
collection, in the order they are returned by the collection's iterator.
Vector V2=new Vector(V1);
 Vector(int initialCapacity): Constructs an empty vector with the specified initial capacity and
with its capacity increment equal to zero.
Vector V1=new Vector(100);
 Vector(int initialCapacity, int capacityIncrement): Constructs an empty vector with the specified
initial capacity and capacity increment.
Vector V1=new Vector(100,10);

PROGRAM:
import java.util.*;
public class VectorDemo {
public static void main(String args[]) {
//Create a vector
Vector<String> V1= new Vector<String>();
//Adding elements using add() method of List
V1.add("AAA");
V1.add("BBB");
V1.add("CCC");
V1.add("DDD");
System.out.println("Vector V1: "+V1);
System.out.println("Vector V1 size: "+V1.size());
System.out.println("Vector V1 capacity: "+V1.capacity());
//Adding elements using addElement() method of Vector
for (int i=1;i<=10;i++)
V1.addElement("EEE");
System.out.println("Vector V1: "+V1);
System.out.println("Vector V1 size: "+V1.size());
System.out.println("Vector V1 capacity: "+V1.capacity());
//Adding elements using add() method of Vector
V1.add("GGG");
System.out.println("Vector V1: "+V1);
System.out.println("Vector V1 size: "+V1.size());
System.out.println("Vector V1 capacity: "+V1.capacity());
}
}
 Stack:
 The stack is the subclass of Vector.
 It implements the last-in-first-out data structure, i.e., Stack.
 The stack contains all of the methods of Vector class and also provides its methods like
boolean push(), boolean peek(), boolean push(object o), which defines its properties.
PROGRAM:
import java.util.*;
public class StackDemo{
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("AAA");
stack.push("BBB");
stack.push("CCC");
stack.push("DDD");
stack.push("EEE");
System.out.println("Stack:"+stack);
System.out.println("Poped Element:"+stack.pop());
/*Iterator<String> itr=stack.iterator();
while(itr.hasNext()){
System.out.println(itr.next());
}*/
System.out.println(stack);
}
}
Set Interface Implementation:
 Child interface of Collection
 If we want to represent a group of individual objects as a single entity where duplicates are not
allowed and insertion order not preserved then we should go for Set.
 extends the Collection interface.
 It represents the unordered set of elements which doesn't allow us to store the duplicate items.
 We can store at most one null value in Set.
 Set is implemented by HashSet, LinkedHashSet, and TreeSet.
 Does not provide any methods only methods of Collection is provided
HashSet:
 Underlying data structure for HashSet is hash table for storage.
 Duplicates are not allowed, contains unique items.
 Insertion order is not preserved and all objects will be inserted based on hash-code objects
 Heterogeneous objects insertion is allowed
 ‘Null’ insertion is possible
 HashSet is best choice if our frequent operation is search
 Implements Serializable and Clonable interface but not RandomAccess
Constructor and Description
HashSet()
Constructs a new, empty set; the backing HashMap instance has default initial capacity (16) and load factor
(0.75).
HashSet(Collection<? extends E> c)
Constructs a new set containing the elements in the specified collection.
HashSet(int initialCapacity)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and default load
factor (0.75).
HashSet(int initialCapacity, float loadFactor)
Constructs a new, empty set; the backing HashMap instance has the specified initial capacity and the specified
load factor.
NOTE: loadFactor is also called as Fill Ratio. The Load Factor is a threshold, if the ratio of the
current element by initial capacity crosses this threshold then the capacity increases, i.e. new object
is created.
DemoProgram:
/* Program to demonstrate HashSet */
import java.util.HashSet;
public class HashSetDemo{
public static void main(String[] args) {
// Create HashSet object
HashSet hs = new HashSet(5, 0.5f);
System.out.println(hs.add("one"));
System.out.println(hs.add("two"));
System.out.println(hs.add("three"));
System.out.println(hs.add("four"));
System.out.println(hs.add("five"));
// Print out the HashSet object
System.out.println(hs);
// Add a duplicate item to the HashSet
Boolean b = hs.add("one");
System.out.println("Duplicate item allowed = " + b);
System.out.println(hs);

}
}

LinkedHashSet:
 Child class of HashSet, introduced in 1.4 version.
 Difference:
HashSet LinkedHashSet
Data structure used is Hash Datastucture used is
Table HashTable+Linked List
Insertion order is not preserved Insertion order is preserved
Introduced in 1.2 version Introduced in 1.4 version
 LinkedHashSet is use to develop cache based applications where duplicates are not allowed but
insertion order is preserved.
DemoProgram:
/* Program to demonstrate LinkedHashSet */
import java.util.*;
public class LinkedHashSetDemo{
public static void main(String[] args) {
// Create HashSet object
LinkedHashSet hs = new LinkedHashSet(5);
hs.add("one");
hs.add("two");
hs.add(3);
hs.add(null);
hs.add(12.5);
// Print out the HashSet object
System.out.println(hs);
}
}

SortedSet(I):
 Child interface of Set
 Used when we want to represent a group of individual objects according to some sorting order and
duplicates are not allowed.
 SortedSetMethods:
o Object first()- returns first element of SortedSet
o Object last()- returns last element of SortedSet
o SortedSet headSet(Object obj) – returns SortedSet whose elements are < obj
o SortedSet tailSet(Object obj) – returns SortedSet whose elements are >=obj
o SortedSet subSet(Object obj1, Object obj2) – returns the SortedSet whose elements are
>=ovj1 and < obj2
o Comparator comparator()- returns Comparator object that describes underlying sorting
technique, if default natural sorting is used then it shows null.
 Ex: {11, 12, 13, 14, 15, 16, 17, 18, 19, 20}
o first()  11
o last()  20
o headSet(14) [11, 12, 13, 14]
o tailSet(17)  [17, 18, 19, 20]
o subset(14,17) [14, 15, 16, 17]
o comparator()  null
 NOTE: above methods will be used on SortedSet implemented class objects i.e. TreeSet object.

TreeSet:
 Data Structure used is Balanced Tree
 Duplicates not allowed
 Insertion order not preserved but all objects will be inserted according to some sorting order
 Heterogeneous objects are not allowed, if tried to insert heterogeneous object insertion runtime
exception ClassCastException is raised. [i.e all objects should be homogeneous andcomparable ]
 Null allowed only once.
 TreeSet Constructors:
TreeSet() : Constructs a new, empty tree set, sorted according to the natural ordering of its elements.
TreeSet T1 = new TreeSet()
TreeSet(Collection<? extends E> c) : Constructs a new tree set containing the elements in the
specified collection, sorted according to the natural ordering of its elements.
TreeSet T1 = new TreeSet(C)
TreeSet(Comparator<? super E> comparator) : Constructs a new, empty tree set, sorted according to
the specified comparator.
TreeSet T1 = new TreeSet(C);
TreeSet(SortedSet<E> s): Constructs a new tree set containing the same elements and using the same
ordering as the specified sorted set.
TreeSet T1 = new TreeSet(S)
DemoProgram:
/* Program to demonstrate TreeSet */
import java.util.*;
public class TreeSetDemo{
public static void main(String[] args) {
// Create HashSet object
TreeSet T1 = new TreeSet();
T1.add("one");
T1.add("two");
T1.add("three");
T1.add("four");
T1.add("AAA");
// Print out the TreeSet object
System.out.println(T1);
}
}
NULL value in TreeSet:
 In empty TreeSet null element insertion is possible. After inserting null, if we try to insert another
element then we will get NullPointerException.
 For non-empty TreeSet if we try to insert null element we will get NullPointerException.
NOTE:
o If we are depending on default natural sorting order then objects should be homorgeneous
and comparable. Otherwise we will get runtime exception saying ClassCastException
o An object is said to be comparable if and only if the corresponding class implements
java.lang.comparable interface.
o Sting class and all wrapper classes already implements comparable interface. But
StringBuffer doesn’t implement comparable interface.
Comparable Interface:
 This interface present in java.lang package it contains only method compareTo()
 Syntax: public int compareTo(Object obj)
 Example : obj1.compareTo(obj2)
o Will return –ve if obj1 comes before obj2
o Will return +ve if obj1 comes after obj2
o Will retrun 0 if obj1 and obj2 are equal

Comparator interface
 Comparator interface is used to order the objects of a user-defined class.
 This interface is found in java.util package and contains 2 methods compare() and
equals(element).
 It provides multiple sorting sequences, i.e., you can sort the elements on the basis of any data
member.
 Methods:
public int compare(Object obj1, Object obj2) It compares the first object with the second
object.
public boolean equals(Object obj) It is used to compare the current object with
the specified object.

Difference between Comparable and Comparator


 Comparable and Comparator both are interfaces and can be used to sort collection elements.
Comparable Comparator
1) Comparable provides a single sorting The Comparator provides multiple sorting
sequence. In other words, we can sort the sequences. In other words, we can sort the
collection on the basis of a single element collection on the basis of multiple elements such as
such as id, name, and price. id, name, and price etc.
2) Comparable affects the original class, Comparator doesn't affect the original class, i.e.,
i.e., the actual class is modified. the actual class is not modified.
3) Comparable provides compareTo() Comparator provides compare() method to sort
method to sort elements. elements.
4) Comparable is present A Comparator is present in the java.util package.
in java.lang package.
5) We can sort the list elements of We can sort the list elements of Comparator type
Comparable type by Collections.sort(List, Comparator) method.
by Collections.sort(List) method.

Cursors/Iterators of JAVA:
 A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a Collection or Stream
object’s elements one by one.
 If we want to retrieve Objects from collection one by one then we should go for cursors.
 There are three cursors available in java:
o Enumerations
o Iterator
o ListIterator
Enumerations:
 introduced in 1.0 version
 Enumerations are used to get Objects one by one from the old Collection objects (Legacy
Collections classes eg. Vector, stack, HashTable etc.)
 EX. : Enumeration object can be created using elements() method of vector class
o Enumeration e =v.elements();
 Enumeration defines the following methods
o public boolean hasMoreElements();
o public Object nextElement();
 Limitations:
o Enumeration concept is applicable only for legacy classes and hence it is not a universal
cursor.
o Enumeration gets only read access and can’t perform remove operation.
o Enumeration moves only forward direction.
 DemoProgram:
import java.util.*;
public class EnumarationVectorDemo {
public static void main(String args[]) {
//Create a vector
Vector<String> V1= new Vector<String>();

//Adding elements using addElement() method of Vector


for (int i=1;i<=10;i++)
V1.add("AAA");

//Accessing elements of vector using Enumeration


Enumeration e = V1.elements();
System.out.println("Vector V1: ");
while(e.hasMoreElements())
System.out.println(e.nextElement());
}
}

Iterators:
 Iterator is universal cursor, it can be applied to any Collection Object.
 Iterator can perform read and remove operations.
 Iterator object is created using iterator() method of Collection interface.
o Iterator itr = C.iterator() // C - any Collection object
 Methods
o public boolean hasNext()
o public Object next()
o public void remove()
 Limitations:
o Enumeration and Iterator moves only in forward direction, hence these are single direction
cursors.
o Iterator only performs read and remove operations it can’t perform replacement of objects.
 DemoExample:
/* Program to demonstrate ArrayList*/
import java.util.*;
class IteratorDemo
{
public static void main(String[] args)
{
ArrayList Al = new ArrayList();
for(int i=1;i<=10;i++) // add elements in the Array List
Al.add(i);

System.out.println(Al); // printing the ArrayList

System.out.println("Array Using Iterator");


Iterator itr=Al.iterator();
while(itr.hasNext()){
Integer n=(Integer) itr.next();
if( n%2==0)
System.out.println(n);
else
itr.remove();
}
System.out.println(Al);
}
}

ListIterator:
 ListIterator can move either forward or backward direction, so ListIterator is
bidirectional cursor.
 ListIterator can perform replacement and addition of new objects along with read and
remove operations
 ListIterator object is created using listIterator() method
o ListIterator itr=L.listIterator();// L is any List Object
 ListIterator is child interface of Iterator, hence all methods of Iterator available to
ListIterator.
 Methods of ListIterator
o Forward Direction
 public boolean hasNext()
 public void next()
 public int nextIndex()
o Backward direction
 public boolean hasPreviou()
 public void previous()
 public int previousIndex()
o Other methods
 public void remove()
 public void set(Object new)
 public void add(Object new)
 ListIterator is most powerful cursor but limitation is it is applicable only for List
implemented class objects and its not universal cursor.
 DemoProgram:
/* Program to demonstrate LinkedList */
import java.util.*;
public class ListIteratorDemo{
public static void main(String args[])
{
LinkedList L1=new LinkedList();
L1.add("AAA");
L1.add("BBB");
L1.add("CCC");
L1.add("DDD");
L1.add("EEE");
System.out.println(L1);

System.out.println("Using ListIterator:");
ListIterator ltr=L1.listIterator();
while(ltr.hasNext())
{
String s = (String) ltr.next();
if(s.equals("AAA"))
ltr.remove();
else if(s.equals("CCC"))
ltr.set("GGG");
else if(s.equals("DDD"))
ltr.add("FFF");
}
System.out.println(L1);
}}

Comparison of Cursors:
Property Enumeration Iterator ListIterator
Applicable for only legacy classes Any Collection classes Only List classes
Movement Only forward direction Only forward direction Both forward and backward direction
(Single directional) (Single directional) (Bi-directional)
Accessibility Only read access Both read and remove Read, remove, replace and addition of
new objects
Method for Creation Using elements() method Using iterator() Using listIterator() method of List
Cursor Object of Vector Class method of Collection interface
interface
Methods 2 methods 3 methods 9 methods
hasMoreElements() hasNext() hasNext(), next(), nextIndex(),
nextElement() next() hasPrevious(), Previous (),
remove() PreviousIndex(), remove(), add(),
replace()
Legacy Class Yes 1.0 v No 1.2 v No 1.2v
Implementation of Classes of Cursors:
/* Program to demonstrate Implementation of Classes of cursors*/
import java.util.*;
public class CursorDemo{
public static void main(String args[])
{
Vector v=new Vector();
Enumeration e=v.elements();
Iterator itr=v.iterator();
ListIterator ltr=v.listIterator();
System.out.println(e.getClass().getName());
System.out.println(itr.getClass().getName());
System.out.println(ltr.getClass().getName());
}}
Map
 A Map is useful if you have to search, update or delete elements on the basis of a key.
 There are two interfaces for implementing Map in java: Map and SortedMap, and
Three classes: HashMap, LinkedHashMap, and TreeMap.
Class Description
HashMap HashMap is the implementation of Map, but it doesn't maintain any
order.
LinkedHashMap LinkedHashMap is the implementation of Map. It inherits HashMap
class. It maintains insertion order.
TreeMap TreeMap is the implementation of Map and SortedMap. It maintains
ascending order.
HashMap
 Map contains its own methods. collection terminology is not applicable
 Underlying data-structure forHashMapis hash table
 Duplicates keys are not allowed but values are allowed
 Insertion order is not preserved and it is based on hashcode of keys
 Heterogeneous keys and values are allowed
 ‘Null’ insertion is possible
 Best choice for searching
 Constructors:
HashMap(): Constructs an empty HashMap with the default initial capacity (16)
and the default load factor (0.75).
HashMap(int initialCapacity): Constructs an empty HashMap with the specified
initial capacity and the default load factor (0.75).
HashMap(int initialCapacity, float loadFactor): Constructs an
empty HashMap with the specified initial capacity and load factor.
 Methods:
o void clear() : Removes all of the mappings from this map.
o Object clone() Returns a shallow copy of this HashMap instance: the keys and
values themselves are not cloned.
o boolean containsKey(Object key) :Returns true if this map contains a mapping for
the specified key.
o boolean containsValue(Object value): Returns true if this map maps one or more
keys to the specified value.
o Set<Map.Entry<K,V>>entrySet(): Returns a Set view of the mappings contained in
this map.
o V get(Object key): Returns the value to which the specified key is mapped, or null if
this map contains no mapping for the key.
o boolean isEmpty(): Returns true if this map contains no key-value mappings.
o Set<K>keySet(): Returns a Set view of the keys contained in this map.
o V put(K key, V value): Associates the specified value with the specified key in this
map.
o V putIfAbsent(K key, V value): If the specified key is not already associated with a
value (or is mapped to null) associates it with the given value and returns null, else
returns the current value.
o V remove(Object key): Removes the mapping for the specified key from this map if
present.
o boolean remove(Object key, Object value): Removes the entry for the specified key
only if it is currently mapped to the specified value.
o V replace(K key, V value): Replaces the entry for the specified key only if it is
currently mapped to some value.
o boolean replace(K key, V oldValue, V newValue): Replaces the entry for the
specified key only if currently mapped to the specified value.
o int size(): Returns the number of key-value mappings in this map.
o Collection<V>values(): Returns a Collection view of the values contained in this
map.
 Demo Program HashMap:
/* Program to demonstrate HashMap */
import java.util.HashMap;
public class HashMapDemo{
public static void main(String[] args) {
// Create HashMap object
HashMap<String, Integer> hm = new HashMap<String, Integer>();
//adding data in hashmap object with put method
hm.put("Java Script",1001);
hm.put("Big Data",1002);
hm.put("Data Science",1003);
hm.put("Android Tech.",1004);
// Print out the HashMap object
System.out.println(hm);
//Getting Value with Key using function get
System.out.println(hm.get("Big Data"));

System.out.println("Keys are: " + hm.keySet());


System.out.println("Values are:"+hm.values());
}
}
HashTable:
 Hash table Underlying data structure is hash table.
 Duplicates keys are not allowed but values can be duplicated.
 Insertion order is not preserved.
 Heterogeneous keys and values allowed.
 Null not allowed.
 Thread safe .
 Best choice for Searching.
 Default initial capacity is 11
 Constructors:
Hashtable() It creates an empty hashtable having the initial default
capacity and load factor.
Hashtable(int capacity) It accepts an integer parameter and creates a hash table that
contains a specified initial capacity.
Hashtable(int capacity, float It is used to create a hash table having the specified initial
loadFactor) capacity and loadFactor.
 Methods:
void clear() It is used to reset the hash table.
Object clone() It returns a shallow copy of the Hashtable.
Enumeration elements() It returns an enumeration of the values in the hash table.
Set<Map.Entry<K,V>> entrySet() It returns a set view of the mappings contained in the map.
boolean equals(Object o) It is used to compare the specified Object with the Map.
int hashCode() It returns the hash code value for the Map
Enumeration<K> keys() It returns an enumeration of the keys in the hashtable.
Set<K> keySet() It returns a Set view of the keys contained in the map.
V put(K key, V value) It inserts the specified value with the specified key in the
hash table.
boolean remove(Object key, Object It removes the specified values with the associated specified
value) keys from the hashtable.
V replace(K key, V value) It replaces the specified value for a specified key.
boolean replace(K key, V oldValue, It replaces the old value with the new value for a specified
V newValue) key.
Collection values() It returns a collection view of the values contained in the
map.
boolean contains(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsValue(Object value) This method returns true if some value equal to the value
exists within the hash table, else return false.
boolean containsKey(Object key) This method return true if some key equal to the key exists
within the hash table, else return false.
boolean isEmpty() This method returns true if the hash table is empty; returns
false if it contains at least one key.
V get(Object key) This method returns the object that contains the value
associated with the key.
V remove(Object key) It is used to remove the key and its value. This method
returns the value associated with the key.
int size() This method returns the number of entries in the hash table.
DemoProgram of HashTable:
import java.util.Hashtable;
import java.util.Enumeration;

public class HashTableDemo {

public static void main(String[] args) {


// Creating a Hashtable
//Hashtable<String, String> hashtable = new Hashtable<String, String>();
Hashtable hashtable = new Hashtable ();
// Adding Key and Value pairs to Hashtable
hashtable.put("Key1","Chaitanya");
hashtable.put("Key2","Ajeet");
hashtable.put("Key3","Peter");
hashtable.put("Key4","Ricky");
hashtable.put("Key5","Mona");
hashtable.put(106,"AAA");
hashtable.put(107,”FFFF”);

Enumeration names = hashtable.keys();


String key;
while(names.hasMoreElements()) {
key = (String) names.nextElement();
System.out.println("Key: " +key+ " & Value: " + hashtable.get(key));
}

hashtable.replace("Key5","Maragret");
System.out.println("Hashtable After Changing value of Key5:"+hashtable);

}
}
TreeMap
 Underlying data structure is RED-BLACK TREE
 Duplicates keys are not allowed but values can be duplicated
 Insertion order is not preserved preserved and it is based on some sorting order of keys
 Heterogeneous keys and values not allowed
 Null acceptance is not there

DemoProgram:
import java.util.*;
public class TreeMapDemo {
public static void main(String args[]) {
TreeMap<Integer,String> tm=new TreeMap<Integer,String>();
tm.put(104,"AAA");
tm.put(103,"BBB");
tm.put(102,"CCC");
tm.put(101,"DDD");
System.out.println("Before invoking remove() method");
for(Map.Entry m: tm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
tm.remove(102);
System.out.println("After invoking remove() method");
for(Map.Entry m:tm.entrySet())
{
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
9-Key Interfaces of Collection Framework
 Collection(I):
 If we want to represent a group of individual objects as a single entity then we should go for
Collection.
 Collection interface defines the most common methods which are applicable for any
Collection object.
 In general collection interface is considered as root interface of Collection Framework.
 There is no concrete class which implements Collection interface directly.
Difference between Collection Vs Collections
Collection is an interface which can be used to represent a group of indivisual objects as a single entity.
Collections is an utility class present in java.util package to define several utility methods(sorting,
searching…) for collection objects.
 List(I):
 List is child interface of Collection
 If we want to represent a group of individual objects as a single entity where duplicates are
allowed and insertion order is preserved then we should go for List.

NOTE: Vector and Stack are called as Legacy Classes as they are from older version of JAVA.

Legacy class is a term that refers to a class or module in a software program that has been inherited
from an older version of the software or system. In Java, legacy classes are the classes and interfaces
that formed the collections framework in the earlier versions of Java and have now been restructured or
re-engineered.

 Set(I):
 Child interface of Collection
 If we want ot represent a group of individual objects as a single entity where duplicates are
not allowed and insertion order not preserved then we should go for Set.

Difference between List and Set:


LIST SET
List represents ordered collection of elements and Set represents a collection of elements. Order of the
preserves the order of elements in which they are elements may change in the set.
entered
List allows duplicate values. Set does not allow duplicate values to be stored.
Accessing elements by index is possible in List. Accessing elements by their index is not possible in
Set.
List allows null elements. Set does not allow null elements.

 SortedSet(I):
 Child interface of Set
 If we want to represent a group of individual objects as a single entity where duplicates are
not allowed but all objects should be inserted according to some sorting order then we should
go for SortedSet.
 NavigableSet(I):
 Child interface of SortedSet it defines several methods For navigation purposes.

 Queue(I):
 Child interface of Collection
 If we want to represent a group of individual objects prior to processing then we should
go for Queue
 Ex.: before sending a email all mail-id’s we have to store somewhere and in which order
we saved in the same order mail’s should be delivered (First In First Out) for this
requirement Queue concept is the best choice.
NOTE: All interfaces i.e. Colletion, List, Set, SortedSet, NavigableSet, Queue are meant for
representing a group of individual objects.
If we want to represent a group of objects as key value pairs then we should go for Map Interface.

 Map(I):
 Map is not child interface of Collection.
 If we want to represent a group of individual objects as key value pairs then we should use
Map.
 Both key and value are objects, duplicated keys are not allowed but values can be duplicated.

 SortedMap(I):
 Child interface of Map
 If we want to represent a group of key value pairs according to some sorting order of keys
then we should go for SortedMap

 NavigableMAp(I):
 Child interface of sorted map, it defines several utility methods for navigation purpose.
purpose

Collection Interface:
 If we want to group of individual objects as a single entity then we should go for Collection.
 In general collection interface is considered as root interface of Collection Framework.
 Collection interface defines the most common methods which are applicable for any
Collection object.
IMPORTANT Methods:
 boolean add(Object o)
 boolean addAll(Collection c)
 boolean remove(Object o)
 boolean removeAll(Collection c) – to remove all objects except those present in c
 void clear()
 boolean contains(Object o)
 boolean containsAll(Collection c)
 boolean isEmpty()
 int size()
 object [] toArray()
 Iterator iterator()
NOTE: Collection interface doesn’t contain any method to retrieve objects there is no concrete class
which implements collection class directly.

LIST Interface:
 Child interface of Collection
 If we want to represent a group of individual objects as a single entity where duplicates are allowed
and insertion order is preserved then we should go for List.
 We can differentiate duplicates by using index.
 We can preserve insertion order by using index, hence index play very important role in list interface.

---------------xxxxxxxxxxx---------------

You might also like