




























































































Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
Community
Ask the community for help and clear up your study doubts
Discover the best universities in your country according to Docsity users
Free resources
Download our free guides on studying techniques, anxiety management strategies, and thesis advice from Docsity tutors
Java Frame work Collection its explained about the frame work of java.
Typology: Lecture notes
1 / 107
This page cannot be seen from the preview
Don't miss anything!
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
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
8 ListIterator
Returns a list iterator over the elements of this list starting from the specified index. 9 List
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.
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.
class ArrayListDemo { public static void main(String[] args) { 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 } }
class ArrayListDemo { public static void main(String[] args) { 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.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()); } } }
class ArrayListDemo { public static void main(String[] args) { ArrayList
list.add(100);
list.add(null);
list.add(null);
System.out.println(list); //Output : [100, null, null] } }
class ArrayListDemo { public static void main(String[] args) { 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).
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
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] } }
class ArrayListDemo { public static void main(String[] args) { ArrayList
positions.
retrieved from another end called 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.
() 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 :
methods return null to indicate Deque is empty.
with the Deque.
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
Properties Of SortedSet Interface :
time.
creating a SortedSet, elements will be placed in ascending order.
randomly. i.e Random access is denied.
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
Returns a view of this set whose elements are in the range from ‘fromElement’ to ‘toElement’. 10 NavigableSet
Properties Of NavigableSet Interface :
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 } }
public class MainClass { public static void main(String[] args) { 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] } }
public class MainClass { public static void main(String[] args) { 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] } }
from any arbitrary position. ? 1 2 3 4 5 6 7 8 9
public class MainClass { public static void main(String[] args) { 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] } }
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.
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.add("First");
list.add("Second");
list.add("Third");
list.add("Fourth");
System.out.println(list); //Output : [First, Second, Third, Fourth] } }
public class MainClass { public static void main(String[] args) { 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 } }
class IteratorAndListIterator { public static void main(String[] args) { List
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()); }
//Traversing list elements in forward direction using ListIterator
ListIterator listIterator = list.listIterator();
while (listIterator.hasNext()) { System.out.println(listIterator.next()); }
//Traversing list elements in backward direction using ListIterator
while (listIterator.hasPrevious()) { System.out.println(listIterator.previous()); }
import java.util.ArrayList; import java.util.List; import java.util.ListIterator;
class IteratorAndListIterator { public static void main(String[] args) { List
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()); }
while (listIterator.hasPrevious()) { //Getting index of previous element
System.out.println(listIterator.previousIndex()+" : "+listIterator.previous()); }