Ch1 Collections
Ch1 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;
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
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’.
-
-
-
-
-
-
- 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
- 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: 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("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>();
}
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.
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>();
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);
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"));
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.
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---------------