Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

collection Frame work of java, Lecture notes of Java Programming

Java Frame work Collection its explained about the frame work of java.

Typology: Lecture notes

2018/2019

Uploaded on 03/17/2019

Mahesh6495
Mahesh6495 🇮🇳

1 document

1 / 107

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
Collection Framework – Class Hierarchy
Why Collection Framework?
Collections are nothing but group of objects stored in well dened manner. Earlier, Arrays are used to represent these
group of objects. But, arrays are not re-sizable. size of the arrays are xed. Size of the arrays can not be changed once
they are dened. This causes lots of problem while handling group of objects. To overcome this drawback of arrays,
Collection framework or simply collections are introduced in java from JDK 1.2.
Although, there were classes like Dictionary, Vector, Stack and Properties which handle group of objects better
than the arrays. But, each of them handle the objects dierently. The way you use Dictionary class is totally dierent
from the way you use Stack class and the way you use Vector class is dierent from the way you use Properties
class. Hence, there needed a central and unifying theme to handle the group of objects. The collection framework is
the answer to that.
What is Collection Framework In Java?
Collection Framework in java is a centralized and unied theme to store and manipulate the group of objects. Java
Collection Framework provides some pre-dened classes and interfaces to handle the group of objects. Using
collection framework, you can store the objects as a list or as a set or as a queue or as a map and perform
operations like adding an object or removing an object or sorting the objects without much hard work.
Class Hierarchy Of Collection Framework :
All classes and interfaces related to Collection Framework are placed in java.util package. java.util.Collection class
is at the top of class hierarchy of Collection Framework. Below diagram shows the class hierarchy of collection
framework.
The entire collection framework is divided into four interfaces.
1) List —> It handles sequential list of objects. ArrayList, Vector and LinkedList classes implement this interface.
2) Queue —> It handles special list of objects in which elements are removed only from the head. LinkedList and
PriorityQueue classes implement this interface.
3) Set —> It handles list of objects which must contain unique element. This interface is implemented by HashSet
and LinkedHashSet classes and extended by SortedSet interface which in turn, is implemented by TreeSet .
4) Map —> This is the one interface in Collection Framework which is not inherited from Collection interface. It
handles group of objects as Key/Value pairs. It is implemented by HashMap and HashTable classes and extended by
SortedMap interface which in turn is implemented by TreeMap.
Three of above interfaces (List, Queue and Set) inherit from Collection interface. Although, Map is included in
collection framework it does not inherit from Collection interface.
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41
pf42
pf43
pf44
pf45
pf46
pf47
pf48
pf49
pf4a
pf4b
pf4c
pf4d
pf4e
pf4f
pf50
pf51
pf52
pf53
pf54
pf55
pf56
pf57
pf58
pf59
pf5a
pf5b
pf5c
pf5d
pf5e
pf5f
pf60
pf61
pf62
pf63
pf64

Partial preview of the text

Download collection Frame work of java and more Lecture notes Java Programming in PDF only on Docsity!

Collection Framework – Class Hierarchy

Why Collection Framework? Collections are nothing but group of objects stored in well defined manner. Earlier, Arrays are used to represent these group of objects. But, arrays are not re-sizable. size of the arrays are fixed. Size of the arrays can not be changed once they are defined. This causes lots of problem while handling group of objects. To overcome this drawback of arrays, Collection framework or simply collections are introduced in java from JDK 1.2. Although, there were classes like Dictionary , Vector , Stack and Properties which handle group of objects better than the arrays. But, each of them handle the objects differently. The way you use Dictionary class is totally different from the way you use Stack class and the way you use Vector class is different from the way you use Properties class. Hence, there needed a central and unifying theme to handle the group of objects. The collection framework is the answer to that. What is Collection Framework In Java? Collection Framework in java is a centralized and unified theme to store and manipulate the group of objects. Java Collection Framework provides some pre-defined classes and interfaces to handle the group of objects. Using collection framework, you can store the objects as a list or as a set or as a queue or as a map and perform operations like adding an object or removing an object or sorting the objects without much hard work. Class Hierarchy Of Collection Framework : All classes and interfaces related to Collection Framework are placed in java.util package. java.util.Collection class is at the top of class hierarchy of Collection Framework. Below diagram shows the class hierarchy of collection framework.

The entire collection framework is divided into four interfaces. 1) List —> It handles sequential list of objects. ArrayList , Vector and LinkedList classes implement this interface. 2) Queue —> It handles special list of objects in which elements are removed only from the head. LinkedList and PriorityQueue classes implement this interface. 3) Set —> It handles list of objects which must contain unique element. This interface is implemented by HashSet and LinkedHashSet classes and extended by SortedSet interface which in turn, is implemented by TreeSet. 4) Map —> This is the one interface in Collection Framework which is not inherited from Collection interface. It handles group of objects as Key/Value pairs. It is implemented by HashMap and HashTable classes and extended by SortedMap interface which in turn is implemented by TreeMap. Three of above interfaces (List, Queue and Set) inherit from Collection interface. Although, Map is included in collection framework it does not inherit from Collection interface.

Collection Framework – Collection Interface

Collection interface is the root level interface in the collection framework. List, Queue and Set are all sub interfaces of Collection interface. JDK does not provide any direct implementations of this interface. But, JDK provides direct implementations of it’s sub interfaces. Collection interface extends Iterable interface which is a member of java.lang package. Iterable interface has only one method called iterator(). It returns an Iterator object, using that object you can iterate over the elements of Collection. Here is the class diagram of Collection interface.

Collection interface contains total 15 abstract methods. 14 of it’s own and one is inherited from Iterable interface. Here is the list and descriptions of those methods.

SL No. Method Description 1 int size() Returns the number of elements in this collection 2 boolean isEmpty() Checks whether this collection is empty or not. If collection is empty, it returns true otherwise it returns false 3 boolean contains(Object o) Checks whether this collection has specified element. 4 Iterator iterator() Returns an iterator over the collection. 5 Object[] toArray() It returns an array containing all elements of this collection. 6 T[] toArray(T[] a) It returns an array of specified type containing all elements of this collection. 7 boolean add(E e) This method adds specified element to this collection. It returns true if element is added successfully to the collection otherwise it returns false. 8 boolean remove(Object o) Removes the specified element from this collection. 9 boolean containsAll(Collection<?> c) It checks whether this collection contains all elements of passed collection. 10 boolean addAll(Collection<? extends E> c)

Adds all elements of the passed collection to this collection.

11 boolean removeAll(Collection<?> c) Removes all elements of this collection which are also elements of passed collection. 12 boolean retainAll(Collection<?> c) Retains only those elements in this collection which are also elements of passed collection.

is the class diagram of List interface.

Additional Methods Of List Interface : There are 9 additional methods included in List interface along with the methods inherited from Collection Interface. Here is the list and the details of those methods.

SL NO Methods Descriptions 1 E get(int index) Returns element at the specified position. 2 E set(int index, E element) Replaces an element at the specified position with the passed element. 3 void add(int index, E element) Inserts passed element at a specified index. 4 E remove(int index) Removes an element at specified index. 5 int indexOf(Object o) It returns an index of first occurrence of passed object. 6 int lastIndexOf(Object o) It returns an index of last occurrence of passed object. 7 ListIterator listIterator() It returns a list iterator over the elements of this list.

8 ListIterator listIterator(int index)

Returns a list iterator over the elements of this list starting from the specified index. 9 List subList(int fromIndex, int toIndex)

Returns sub list of this list starting from ‘fromIndex’ to ‘toIndex’.

Advantages Of Using ArrayList Over Arrays

Array and ArrayList are most used data types while developing any java applications. Both are used to store group of objects. In this post I have tried to list down the advantages of using ArrayList over Arrays. Before discussing the advantages of ArrayList, let’s see what are the drawbacks of arrays.

• Arrays are of fixed length. You can not change the size of the arrays once they are created.

• You can not accommodate an extra element in an array after they are created.

• Memory is allocated to an array during it’s creation only, much before the actual elements are added to it.

Because of these drawbacks, use of arrays are less preferred. Instead of arrays, you can use ArrayList class which addresses all these drawbacks. Here are some advantages of using ArrayList over arrays.

  1. You can define ArrayList as re-sizable array. Size of the ArrayList is not fixed. ArrayList can grow and shrink dynamically. ?

class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList();

list.add("ONE");

list.add("TWO");

list.add("THREE");

System.out.println(list.size()); //Output : 3

//Inserting some more elements list.add("FOUR");

list.add("FIVE");

System.out.println(list.size()); //Output : 5

//Removing an element list.remove("TWO");

System.out.println(list.size()); //Output : 4 } }

  1. Elements can be inserted at or deleted from a particular position. ? 1 2 3 4 5 6 7 8 9

class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList();

list.add("ZERO");

list.add("TWO");

list.add("FOUR");

System.out.println(list); //Output : [ZERO, TWO, FOUR]

list.add(2, "THREE"); //Inserting an element at index 2

list.add(1, "ONE"); //Inserting an element at index 1

System.out.println(list); //Output : [ZERO, ONE, TWO, THREE, FOUR]

list.remove(3); //Removing an element from index 3

public static void main(String[] args) { ArrayList list = new ArrayList();

list.add("ONE");

list.add("TWO");

list.add("THREE");

list.add("FOUR");

ListIterator iterator = list.listIterator();

System.out.println("Elements in forward direction");

while (iterator.hasNext()) { System.out.println(iterator.next()); }

System.out.println("Elements in backward direction");

while (iterator.hasPrevious()) { System.out.println(iterator.previous()); } } }

  1. ArrayList can hold multiple null elements. ? 1 2 3 4 5 6 7 8 9

class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList();

list.add(100);

list.add(null);

list.add(null);

System.out.println(list); //Output : [100, null, null] } }

  1. ArrayList can hold duplicate elements. ? 1 2 3 4 5 6 7 8 9

class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList();

list.add(100);

list.add(100);

list.add(100);

System.out.println(list); //Output : [100, 100, 100] } }

(Above two advantages(7 and 8) are also applicable to arrays. But, you can treat them as bonus with all above advantages of ArrayList.)

How To Modify An ArrayList? You can modify an ArrayList elementarily (Only one element is added or removed or updated) or in bulk (More than one elements are added or removed or updated).

  1. Elementary Modification Operations On ArrayList :

The following methods are used to perform elementary modification operations on ArrayList. boolean add(E e) : This method appends an element at the end of this List. If the ArrayList is empty then there will be exactly one element after this operation. void add(int index, E element) : This method inserts an element at the specified position. boolean remove(Object o) : It removes first occurrence of specified element from the list. E remove(int index) : This method removes an element from the specified position. E set(int index, E element) : This method replaces an element at the specified position with the passed element. Here is an example to show elementary modifications on ArrayList. ?

class ArrayListDemo { public static void main(String[] args) { ArrayList list = new ArrayList(); list.add("ONE"); //Adds "ONE" at the end of the list list.add("TWO"); //Adds "TWO" at the end of the list list.add("THREE"); //Adds "THREE" at the end of the list list.add("FOUR"); //Adds "FOUR" at the end of the list System.out.println(list); //Output : [ONE, TWO, THREE, FOUR] list.add(3, "INSERTED"); //Inserts "INSERTED" at position 3

System.out.println(list); //Output : [ONE, TWO, THREE, INSERTED, FOUR]

list.add(1, "INSERTED"); //Inserts "INSERTED" at position 1

System.out.println(list); //Output : [ONE, INSERTED, TWO, THREE, INSERTED, FOUR]

list.remove("INSERTED"); //Removes first occurence of "INSERTED"

System.out.println(list); //Output : [ONE, TWO, THREE, INSERTED, FOUR]

list.remove(3); //Removes an element at position 3

System.out.println(list); //Output : [ONE, TWO, THREE, FOUR]

list.set(3, "REPLACED"); //Replaces an element at position 3 with "REPLACED"

System.out.println(list); //Output : [ONE, TWO, THREE, REPLACED] } }

  1. Bulk Modification Operations On ArrayList : The following methods are used to perform bulk modifications on ArrayList. boolean addAll(Collection<? extends E> c) : This method appends all elements of the passed collection at the end of this list. boolean addAll(int index, Collection<? extends E> c) : This method inserts all elements of the passed collection at the specified position in this list. boolean removeAll(Collection<?> c) : This method removes all elements of this list which are also elements of the passed collection. boolean retainAll(Collection<?> c) : This method retains only those elements in this list which are also elements of the passed collection. void clear() : This method removes all elements of the list. Here is an example to perform bulk modifications on ArrayList. ?

class ArrayListDemo { public static void main(String[] args) { ArrayList list1 = new ArrayList(); list1.add("ONE"); list1.add("TWO"); list1.add("THREE"); list1.add("FOUR"); System.out.println(list1); //Output : [ONE, TWO, THREE, FOUR]

• Unlike a normal list, queue is not random access. i.e you can’t set or insert or get elements at an arbitrary

positions.

• In most of cases, elements are inserted at one end called tail of the queue and elements are removed or

retrieved from another end called head of the queue.

• In the Queue Interface, there are two methods to obtain and remove the elements from the head of the queue.

They are poll() and remove(). The difference between them is, poll() returns null if the queue is empty and remove() throws an exception if the queue is empty.

• There are two methods in the Queue interface to obtain the elements but don’t remove. They are peek

() and element(). peek() returns null if the queue is empty and element() throws an exception if the queue is empty. Methods Of Queue Interface: Here are the methods of Queue interface. Some of the methods throw an exception if operation is not possible and some methods return a value (null or false) if operation is not possible.

Operation Throws An Exception If operation is not possible

Returns null or false if operation is not possible Add an element to the queue. add() offer() Retrieve an element from the head of the queue.

element() peek()

Retrieve And Remove an element from the head of the queue.

remove() poll()

Collection Framework – The Deque Interface The Deque is the short name for “Double Ended Queue“. As the name suggest, Deque is a linear collection of objects which supports insertion and removal of elements from both the ends. The Deque interface defines the methods needed to insert, retrieve and remove the elements from both the ends. The Deque interface is introduced in Java SE 6. It extends Queue interface. Here is the hierarchy diagram of Deque interface.

The main advantage of Deque is that you can use it as both Queue (FIFO) as well as Stack (LIFO). The Deque interface has all those methods required for FIFO and LIFO operations. Some of those methods throw an exception if operation is not possible and some methods return a special value (null or false) if operation fails. Here is the list of Deque Methods.

Operation Throws an exception if operation fails.

Returns null or false if operation fails. Insertion Front End addFirst() offerFirst() Rear End addLast() offerLast() Retrieval Front End getFirst() peekFirst() Rear End getLast() peekLast() Retrieval And Removal Front End removeFirst() pollFirst() Rear End removeLast() pollLast()

How Deque – Double Ended Queue Works? As already said, Deque is nothing but the double ended queue. That means, you can insert, retrieve and remove the elements from both the ends. Below diagram shows how Deque works. Deque As Queue : As Deque interface extends Queue interface, it inherits all methods of Queue interface. So, you can use all those inherited methods to perform Queue operations. Along with them, methods defined in the Deque interface can also be used for Queue operations. Below is the list of Queue methods and their equivalent Deque methods.

Queue Methods Equivalent Deque Methods add() addLast() offer() OfferLast() element() getFirst() peek() peekFirst() remove() removeFirst() poll() pollFirst()

Deque As Stack : Deque interface has two more methods – pop() and push(). These two methods make Deque to function as a stack (Last-In-First-Out). Along with these two methods, you can also use addFirst(), peekFirst() and removeFirst() for stack operations. Below is the list of Stack methods and their equivalent methods of Deque.

Stack Methods Equivalent Deque Methods push() addFirst() pop() removeFirst() peek() peekFirst()

Properties Of Deque :

• Unlike Queue, Deque can have null elements. But, it is recommended not to insert null elements as many

methods return null to indicate Deque is empty.

• Deque can have duplicate elements.

• You can’t set or get or insert the elements at an arbitrary position of Deque. i.e Random access is not possible

with the Deque.

• You can use removeFirstOccurrenec(E e), removeLastOccurrence(E e) and remove(E e) methods to delete the

elements from the Deque.

Collection Framework – The Set Interface The Set interface defines a set. The set is a linear collection of objects with no duplicates. Duplicate elements are not allowed in a set. The Set interface extends Collection interface. Set interface does not have it’s own methods. All it’s methods are inherited from Collection interface. The only change that has been made to Set interface is that add() method will return false if you try to insert an element which is already present in the set. Below is the hierarchy diagram of Set interface.

Methods Of SortedSet Interface : SortedSet interface defines 6 more methods along with the inherited methods from Set interface. These methods make the processing of SortedSet elements more easy. Here is the list of SortedSet interface methods.

SL NO. SortedSet Interface Methods Description 1 Comparator<? super E> comparator() Returns Comparator used to order the elements. If no comparator is supplied, it returns null. 2 SortedSet subSet(E fromElement, E toElement) Returns a portion of this set whose elements range from ‘fromElement’ (Inclusive) and ‘toElement’ (Exclusive). 3 SortedSet headSet(E toElement) Returns a SortedSet whose elements are in the range from first element of the set (Inclusive) to ‘toElement’ (exclusive). 4 SortedSet tailSet(E fromElement) Returns a SortedSet whose elements are in the range from ‘fromElement’ (Inclusive) to last element of the set (exclusive). 5 E first() Returns first element of the SortedSet. 6 E last() Returns last element of the SortedSet.

Properties Of SortedSet Interface :

• SortedSet can not have null elements. If you try to insert null element, it gives NullPointerException at run

time.

• As SortedSet is a set, duplicate elements are not allowed.

• SortedSet elements are sorted according to supplied Comparator. If you don’t mention any Comparator while

creating a SortedSet, elements will be placed in ascending order.

• Inserted elements must be of Comparable type and they must be mutually Comparable.

• You can retrieve first element and last elements of the SortedSet. You can’t access SortedSet elements

randomly. i.e Random access is denied.

• SortedSets returned by headSet(), tailSet() and subSet() methods are just views of the original set. So,

changes in the returned set are reflected in the original set and vice versa.

Collection Framework – The NavigableSet Interface The NavigableSet is a SortedSet with navigation facilities. The NavigableSet interface provides many methods through them you can easily find closest matches of any given element. It has the methods to find out less than, less than or equal to, greater than and greater than or equal of any element in a SortedSet. The NavigableSet interface extends SortedSet interface. Here is the hierarchy diagram of NavigableSet Interface.

Methods Of NavigableSet Interface :

SL NO. NavigableSet Interface Methods Description 1 E lower(E e) Returns greatest element in this set which is strictly less than the given element. 2 E floor(E e) Returns greatest element in this set which is less than or equal to the given element. 3 E ceiling(E e) Returns the least element in this set which is greater than or equal to the given element. 4 E higher(E e) Returns the least element in this set which is strictly greater than the given element. 5 E pollFirst() Retrieves and removes the first element in this set. 6 E pollLast() Retrieves and removes last element in this set. 7 NavigableSet descendingSet() Returns reverse order view of this set. 8 Iterator descendingIterator() Returns an iterator over the elements of this set in descending order. 9 NavigableSet subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive)

Returns a view of this set whose elements are in the range from ‘fromElement’ to ‘toElement’. 10 NavigableSet headSet(E toElement, boolean inclusive) Returns a view of this set whose elements are in the range from first element of this set to ‘toElement’. 11 NavigableSet tailSet(E fromElement, boolean inclusive) Returns a view of this element whose elements are in the range from ‘fromElement’ to last element of this set.

Properties Of NavigableSet Interface :

• NavaigableSet can’t have null elements.

• NavigableSet doesn’t support duplicate elements.

• NavigableSet can be traversed and accessed in either ascending or descending order.

• Methods subSet(), headSet() and tailSet() differ from SortedSet interface in taking additional arguments

describing whether upper bound and lower bound are inclusive or exclusive. Collection Framework – The ArrayList Class

In java, normal arrays are of fixed length. You can not change the size of arrays once they are defined. That means, you must know in advance how large an array you want. But sometimes, you may not know how large an array you want. To overcome this situation, ArrayList is introduced in Collection framework. ArrayList, in simple terms, can be defined as re-sizable array. ArrayList is same like normal array but it can grow and shrink dynamically to hold any number of elements. ArrayList is a sequential collection of objects which increases or decreases in size as we add or delete the elements.

27 System.out.println(list.size());^ //Output : 3 } }

• ArrayList can have any number of null elements.

public class MainClass { public static void main(String[] args) { ArrayList list = new ArrayList<>();

//Adding elements to ArrayList

list.add(100);

list.add(null);

list.add(2000);

list.add(null);

list.add(null);

//ArrayList having 3 null elements

System.out.println(list); //Output : [100, null, 2000, null, null] } }

• ArrayList can have duplicate elements.

public class MainClass { public static void main(String[] args) { ArrayList list = new ArrayList<>();

//Adding elements to ArrayList

list.add(100);

list.add(100);

list.add(100);

list.add(100);

//ArrayList having 4 duplicate elements

System.out.println(list); //Output : [100, 100, 100, 100] } }

• As ArrayList implements RandomAccess, you can get, set, insert and remove elements of the ArrayList

from any arbitrary position. ? 1 2 3 4 5 6 7 8 9

public class MainClass { public static void main(String[] args) { ArrayList list = new ArrayList<>();

//Adding elements to ArrayList

list.add(10);

list.add(20);

list.add(30);

list.add(40);

System.out.println(list); //Output : [10, 20, 30, 40]

//Retrieving element at index 2

System.out.println(list.get(2)); //Output : 30

//Setting value of element at index 2

list.set(2, 2222);

System.out.println(list); //Output : [10, 20, 2222, 40]

//Inserting element at index 1

list.add(1, 1111);

System.out.println(list); //Output : [10, 1111, 20, 2222, 40]

//Removing element from index 3

list.remove(3);

System.out.println(list); //Output : [10, 1111, 20, 40] } }

• When you insert an element in the middle of the ArrayList, the elements at the right side of that position are

shifted one position right and when you delete an element, they will be shifted one position left. This feature of the ArrayList causes some performance issues as shifting of elements is time consuming if ArrayList has lots of elements.

• Elements are placed according to Zero-based index. That means, first element will be placed at index 0 and

last element at index n-1, where ‘n’ is the size of the ArrayList. ? 1 2 3 4 5 6 7 8 9

public class MainClass { public static void main(String[] args) { ArrayList list = new ArrayList();

list.add("First");

list.add("Second");

list.add("Third");

list.add("Fourth");

System.out.println(list); //Output : [First, Second, Third, Fourth] } }

• ArrayList is not synchronized. That means, multiple threads can use same ArrayList simultaneously.

• If you know the element, you can retrieve the position of that element.

public class MainClass { public static void main(String[] args) { ArrayList list = new ArrayList();

//Adding elements to ArrayList

list.add("First");

list.add("Second");

list.add("Third");

Set set = new HashSet(list);

//Traversing set elements using Iterator Iterator iterator3 = set.iterator();

while (iterator3.hasNext()) { System.out.println(iterator3.next()); }

//Traversing list elements using ListIterator ListIterator listIterator1 = list.listIterator();

while (listIterator1.hasNext()) { System.out.println(listIterator1.next()); }

//Traversing queue and set elements using ListIterator is not possible

ListIterator listIterator2 = queue.listIterator(); //Compile time error, there is no such method in Queue

ListIterator listIterator3 = set.listIterator(); //Compile time error, there is no such method in Set } }

  1. Using Iterator, we can traverse the elements only in forward direction. But, using ListIterator you can traverse the elements in both the directions – forward and backward. ListIterator has those methods to support the traversing of elements in both the directions. Iterator Methods : boolean hasNext() –> Checks whether collection has more elements. E next() –> Returns the next element in the collection. void remove() –> Removes the current element in the collection i.e element returned by next(). ListIterator Methods : boolean hasNext() –> Checks whether the list has more elements when traversing the list in forward direction. boolean hasPrevious() –> Checks whether list has more elements when traversing the list in backward direction. E next() –> Returns the next element in the list and moves the cursor forward. E previous() –> Returns the previous element in the list and moves the cursor backward. int nextIndex() –> Returns index of the next element in the list. int previousIndex() –> Returns index of the previous element in the list. void remove() –> Removes the current element in the collection i.e element returned by next() or previous(). void set(E e) –> Replaces the current element i.e element returned by next() or previous() with the specified element. void add(E e) –> Inserts the specified element in the list. ? 1 2 3 4 5 6 7 8 9

class IteratorAndListIterator { public static void main(String[] args) { List list = new ArrayList();

list.add("FIRST");

list.add("SECOND");

list.add("THIRD");

//Traversing list elements in forward direction using Iterator

Iterator iterator = list.iterator();

while (iterator.hasNext()) { System.out.println(iterator.next()); }

// OUTPUT :

// FIRST

// SECOND

// THIRD

//Traversing list elements in forward direction using ListIterator

ListIterator listIterator = list.listIterator();

while (listIterator.hasNext()) { System.out.println(listIterator.next()); }

// OUTPUT :

// FIRST

// SECOND

// THIRD

//Traversing list elements in backward direction using ListIterator

while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); }

// OUTPUT :

// THIRD

// SECOND

// FIRST

  1. Using ListIterator, you can obtain index of next and previous elements. But, it is not possible with Iterator interface. ? 1 2 3 4 5 6 7 8 9

import java.util.ArrayList; import java.util.List; import java.util.ListIterator;

class IteratorAndListIterator { public static void main(String[] args) { List list = new ArrayList();

list.add("FIRST");

list.add("SECOND");

list.add("THIRD");

ListIterator listIterator = list.listIterator();

while (listIterator.hasNext()) { //Getting index of next element

System.out.println(listIterator.nextIndex()+" : "+listIterator.next()); }

// OUTPUT :

// 0 : FIRST

// 1 : SECOND

// 2 : THIRD

while (listIterator.hasPrevious()) { //Getting index of previous element

System.out.println(listIterator.previousIndex()+" : "+listIterator.previous()); }

// OUTPUT :

// 2 : THIRD

// 1 : SECOND

// 0 : FIRST