0% found this document useful (0 votes)
10 views23 pages

Collection_Framework[1]

The document discusses the differences between arrays and collections in programming, highlighting the limitations of arrays such as fixed size and homogeneity, while emphasizing the advantages of collections, which are growable and can hold heterogeneous data. It outlines various interfaces within the Java Collection Framework, including Collection, List, Set, and Map, and their specific functionalities. Additionally, it compares different collection types like ArrayList, LinkedList, and Vector, detailing their characteristics, use cases, and performance implications.

Uploaded by

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

Collection_Framework[1]

The document discusses the differences between arrays and collections in programming, highlighting the limitations of arrays such as fixed size and homogeneity, while emphasizing the advantages of collections, which are growable and can hold heterogeneous data. It outlines various interfaces within the Java Collection Framework, including Collection, List, Set, and Map, and their specific functionalities. Additionally, it compares different collection types like ArrayList, LinkedList, and Vector, detailing their characteristics, use cases, and performance implications.

Uploaded by

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

Notes by vk

Collection Framework...!

What is the need and purpose of


collection: -

An array is an indexed Collection of fixed number of


homogenous data elements. The Main advantage of Array is
we can represent multiple values with a single variable.
So that reusability of the code will be improved.

Limitations of Object type Arrays: -


Arrays are fixed in size i.e. once we created an array with some size
there is no chance of increasing or decreasing its size based on our
requirements. Hence to use arrays compulsory we should know the
size in advance which may not possible always.
Arrays can hold only homogenous data elements.
There is no under laying Data Structure.
Ex...
Student [] s = new Student [1000];
s [0] = new Student (); (correct)
s [1] = new Customer (); (wrong)
But we can resolve this problem by using object Arrays.
Object [] o = new Object [1000];
o [0] = new Student ();
o [1] = new Customer ();
Arrays Concept is not implemented based on some standard data
structure hence readymade method support is not available for every
Notes by vk

requirement we have to write the code explicitly. Which is complexity


of programming.

Collection
Collection is growable in nature.
Collection can hold both homogenous and heterogenous data
elements.
Every Collection class is implemented based on some
standard data structure.

Need of Collections
To overcome the above limitations of Arrays we should go for
Collections.
Collections are growable in nature. i.e. Based on our
requirement we can increase (or) Decrease the size.
Collections can hold both homogeneous & heterogeneous
elements.
Every Collection class is implemented based on some
standard data structure. Hence readymade method support
is available for every requirement. Being a programmer we
have to use this method and we are not responsible to
provide implementation.

Difference between Arrays and


Collections
Arrays Collections
1. Arrays are fixed in size. 1. Collections are growable
in nature. i.e. based on
our requirements we
Notes by vk

can increase or
decrease the size.
2. With respect to memory 2. With respect to
arrays are not collections are
recommended to use. recommended to use.
3. With respect to 3. With respect to
Performance Arrays are performance collections
recommended to use. are not recommended to
use.
4. Arrays can hold only 4. Collections can hold
homogeneous data type both homogeneous and
elements. heterogeneous
elements.
5. There is no underlying 5. Every Collections class
data structure for arrays is implemented based
and hence readymade on some standard data
method support is not structure. Hence
available. readymade method
support is available for
every requirement.
6. Array can hold both 6. Collections can hold
primitives and object only objects but not
types. primitive.

Collection & Collection Framework


Collection:
If we want to represent a group of individual objects as a
single entity then we should go for Collection.
Collection Framework:
It defines several classes and interfaces which can be used a
group of objects as single entity.
Notes by vk

Java C++
Collection Container
Collection Framework STL (Standard Template
Library)

9 (Nine) Key Interface of Collection


Framework
1. Collection(I): (1.2 v)
- If we want to represent a group of individual objects
as a single entity 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.
Note: - There is no concrete class which implements
collection interface directly.

Collection VS Collections
- Collection is an interface which can be used to represent
a group of individual objects as a single entity.
- Collections is a utility class present in java.util.package
to define several methods (like Sorting, Searching.) for
Collection objects.
2. List: (1.2 v)
- 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 preserved then we should go for List.

Collection (1.2 v)
Notes by vk

List (1.2 v)

ArrayList (1.2 v) Linked List (1.2 v) Vector


(1.0 v)

Stack (1.0 v)

3. Set:
- It is the 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.
Collection (1.2 v)

Set (1.2 v)

HashSet (1.2 v)

LinkedHashSet (1.4 v)

Difference Between List & Set

List Set
Notes by vk

Duplicates are allowed Duplicated are not allowed


Insertion order preserved Insertion order not preserved

4. SortedSet:
- It is the 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.
5. NavigableSet:
- It is the child interface of SortedSet if defines several
methods for navigation purposes.

Collection (I) (1.2 v)

Set (I) (1.2 v)

SortedSet (I) (1.2 v)

NavigableSet (I) (1.6 v)

TreeSet (1.2 v)
6. Queue:
- It is 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 mail all mail Id’s we have to store
somewhere and in which order we saved in the same
Notes by vk

order Mail’s should be delivered (First in First out) for


this requirement Queue concept is the best choice,
Collection (I) (1.2v) Legacy Class

Queue (I) (1.5v)

PriorityQueue (1.5v) BlockingQueue (1.5v)

LinkedBlockingQueue (1.5v)

PriorityBliockingQueue (1.5v)

Note:
- All the above interfaces (Collection, List, Set, SortedSet,
NavigableSet and Queue) 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.

7. Map:
- Map is not the child interface of Collection.
- If we want to represent a group of individual objects
as key value pairs then should go for Map.
Ex…
Id No Name
Notes by vk

1001 Varun
1002 vk
Both key and value are objects, duplicated keys are not
allowed but values can be allowed.

Legacy Class
Map (I) (1.2v)
Dictionary
(1.0v)

HashMap (1.2v) WeakHashMap (1.2v) IdentityHashMap


(1.4v) Hash table (1.0v)

LinkedHashMap (1.4v)
Properties (1.0v)

8. SortedMap:
- It is the 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.

Map (I) (1.2v)

SortedMap (I) (1.2v)


9. NavigableMap(I):
Notes by vk

- It is child interface of sorted map, it defines several


utility methods for navigation purpose.

Map (I) (1.2v)

SortedMap (I) (1.2v)

NavigableMap (I) (1.6v)

TreeMap (I) (1.2v)

Iterable
Notes by vk

1. Collection Interface:
- If we want to represent a 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 method of Collection Interface
a. boolean add (Object o)
b. boolean addAll (Collection c)
c. boolean remove (Object o)
d. boolean removeAll (Collection c)
e. boolean retainAll (Collection c)
To remove all objects except those, present in c
f. void clear ()
g. boolean contains (Object o)
Notes by vk

h. boolean containsAll (Collection c)


i. boolean isEmpty ()
j. int size ()
k. Object [] toArray ()
l. Iterator iterator ()

Note:
Collection interface doesn’t contain any method to retrieve
objects there is no concrete which implements collection
class directly.

2. List Interface
- It is the 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 must be 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.

List interface specific methods


a. void add (int index, Object o)
b. boolean addAll (int index, Collection o)
c. object get (int index)
d. object remove (int index)
e. object set (int index, Object new)
f. int indexOf (Object o)
g. int lastIndexOf (Object o)
h. ListIterator listIterator ();
Notes by vk

3. ArrayList
- The underlined data structure Resizable Array or
Growable Array.
- Duplicates are allowed.
- Insertion order is preserved.
- Heterogeneous objects are allowed (except TreeSet &
TreeMap everywhere heterogeneous objects are
allowed].
- Null insertion is possible.

New Capacity = (cc * 3/2) + 1


ArrayList Constructors
a. ArrayList al = new ArrayList ()
- Creates an empty Array list object with default
capacity 10. Once Array List reaches its map capacity
a new Array List will be created with new capacity =
(currentcapacity * 3/) + 1.
b. ArrayList al = new ArrayList (int initialCapacity);
c. ArrayList al = new ArrayList (Collection c);

Ex…
Import java.util.*;
Class ArrayListDemo {
Public static void main (String [] args) {
ArrayList al = new ArrayList ();
al.add (“A”);
al.add (10);
Notes by vk

al.add (“A”);
System,out,println(al); // [A,10,A,null]
al.remove(2);
System.out.println (al); // [A,10, null]
al.add (2, “M”);
al.add (“N”);
System.out.println(al); // [A, 10, M, null, N]
}
}
Usually, we can use Collections to hold and transfer Objects
from one place to another place, to provide support for this
requirement every Collection already implements Serializable
and Cloneable interfaces.
ArrayList and Vector classes implements RandomAccess
interface so that we can access any Random element with
the same speed.
Hence if our frequent operation is retrieval operation then
ArrayList is the best choice.

RandomAccess
Present in java.util package.
It doesn’t contain any methods and it is a Maker interface
Ex…
ArrayList
ArrayList l1 = new ArrayList ();
LinkedList l2 = new LinkedList ();
Notes by vk

System.out.println (l1 instanceOfSerializable); //true


System.out.println (l2 instacneOfCloneable); //true
System.out.println (l1 instanceOfRandomAccess); //true
System.out.println (l2 instanceOfRandomAccess); //false

ArrayList is best choice if our frequent operation is retrieval


operation (Because ArrayList implements RandomAccess
interfaces)
ArrayList is the worst choice if our frequent operation
insertion or deletion in the middle (Because several shift
operations are required).

Difference between ArrayList & Vector


ArrayList Vector
Every method present Every method present in
ArrayList is non synchronize. LinkedList is synchronize.
At a time, multiple threads At a time only one thread is
are allowed to operate on allowed to operate on Vector
ArrayList Object and hence Object is thread safe.
ArrayList is not thread safe.
Treads are not required to Treads are required to wait to
wait to operate on ArrayList, operate on Vector Object and
hence relatively performance hence relatively performance
is high. is low.
Introduced in 1.2 version and Introduced in 1.0 version and
it is non legacy class it is a legacy class

How to get synchronized version of ArrayList Object?


Notes by vk

- By default, ArrayList is Object is non-synchronized but


we can get synchronized version of ArrayList by using
Collection class synchronizedList () method.
o public static List synchronizedList (List I);

public static List synchronizedList (List I)

Non-Synchronized
ArrayList l1 = new ArrayList ();

Synchronized
List I = Collections.synchronizedList (l1);
- Similarly, we can get Synchronized version of Set, Map
Objects by using the following methods of Collections
class.
public static Set synchronizedSet (Set s);

public static Set synchronizedMap (Map m);

LinkedList
- The underlying data structure is Double Linked List.
- Insertion order is preserved.
- Duplicates are allowed.
- Heterogeneous Objects are allowed.
- Null insertion is possible.
LinkedList implements Serializable and Cloneable interfaces
but not RandomAccess interface.
LinkedList is the best choice if our frequent operation is
insertion or deletion in the middle.
LinkedList is the worst choice if our frequent operation is
retrieval operation.
Notes by vk

Usually, we can use LinkedList to implement stacks and


queues to provide support for this requirement LinkedList
class defines following specific methods.
void addFirst ();
void addLast ();
Object getFirst ();
Object getLast ();
Object removeFirst ();
Object removeLast ();

LinkedList Constructors
- LinkedList i1 = new LinkedList ();
Creates an empty LinkedList Object.
- LinkedList l1 = new LinkedList (Collection c);
Creates an equivalent LinkedList Object for the
given Collection.

Ex….
Class LinkedListDemo {
Public static void main(String[] args){
LinkedList l = new LinkedList();
l.add(“vk”);
l.add(30);
l.add(null);
l.add(“vk”);
Notes by vk

l.set(0, “software”);
l.add(0, “venkey”);
l.removeLast();
l.addFirst(“ccc”);
System.out.println(l);
}
}

Difference between ArrayList & LinkedList


ArrayList LinkedList
It is the best choice if our It is the best choice if our
frequent operation is frequent Operation is
retrieval. insertion and deletion.
ArrayList is the worst choice LinkedList is the worst choice
if our frequent operation is if our frequent operation is
insertion or deletion retrieval operation.
Underlying data structure for Underlying data structure is
ArrayList is resizable or Double Linked List.
growable Array.
ArrayList implements LinkedList doesn’t implement
RandomAccess interface. RandomAccess interface.

Vector
- The underlying Data Structure for the vector is resizable
array or growable array.
- Duplicate objects are allowed.
- Insertion order is preserved.
- ‘null’ insertion is possible.
- Heterogeneous objects are allowed.
Notes by vk

- Vector class implemented Serializable, Cloneable and


RandomAccess Interfaces.
- Most of the methods present in Vector are synchronized.
Hence Vector objects Tread-safe.
- Best choice if the frequent operation is retrieval.
Vector specific methods
For adding objects:
add (Object o) [from Collection-List(I)]
add (int index, Object o) [from List]
addElement (Object o) [from Vector]
For removing Objects:
remove (Object o) [from Collection]
removeElement (Object o) [from Vector]
remove (int index) [from List]
removeElementAt (int index) [from Vector]
clear () [from Collection]
removeAllElements ()[from Vector]

For Accessing Elements:


Object get (int index) [from Collection]
Object elementAt (int index) [from Vector]
Object firstElement ()[from Vector]
Object lastElement () [from Vector]

Other Methods:
Notes by vk

int size ();


int capacity ();
Enumeration elements ();
Constructors of vector class
1. Vector v = new Vector();
- Creates an empty vector object with default initial
capacity 10, Once vector reaches it’s max capacity a
new vector Object will be created with new capacity =
2 * current capacity.
2. Vector v = new Vector (int initialCapacity);
- Created an empty Vector Object with specified initial
capacity.
3. Vector v = new Vector (int initialCapacity, int
incrmentalCapacity);
4. Vector v = new Vector(Collection c)
- Creates an equivalent Vector Object for the given
Collection.
Ex…!
Demo program for vector
Import java.util.*;
Class VectorDemo1
{
Public static void main(String[] args){
Vector v = new Vector();
System.out.println(v.capacity()); //[10]
For(int I = 1; I <=10; i++){
v.addElemnet(i);
}
Notes by vk

System.out.println(v.capacity()); //[10]
v.addElement(“A”);
System.out.println(v.capacity());
System.out.println(v);//[1,2,,,,,,10,A] or [20]
}
}

Stack
- It is a child class of Vector.
- It is specially designed class for Last in First Out order
(LIFO)
Constructor of Stack
- Stack s = new Stack ();
Methods in Stack
1. Object push (Object obj);
- For inserting an object to the stack
2. Object pop ();
- To removes and returns top of the stack.
3. Object peak ();
- To returns the top of the stack without removal of
object.
4. Int search (Object obj);
- If the specified object is available, it returns its offset
from top of the stack.
- If the object is not available then it returns -1.
5. Object pop (0;
- For inserting an object to the stack.
Three cursors of Java
Notes by vk

- If we want to retrieve Objects one by one from the


Collection, then we should go for Cursors.
- There are three types of cursors are available in java.
 Enumeration
 Iterator
 ListIterator
a. Enumeration
- Introduced in 1.0 version (for Legacy).
- We can use Enumeration to get Objects one by one
from the old Collection Objects (Legacy Collections).
- We can create Enumeration Object by using elements
() method of Vector class.
Public Enumeration elements ();
Ex…!
Enumeration e = v.elements ();
Enumeration defines the following two methods
 public boolean hasMoreElementa ();
 public Object nextElement ();
Program for Enumeration
Import java.util.*;
Class EnumerationDemo{
Public static void main (String[] arga){
Vector v = new Vector ();
For (int i = 0; i <= 10; i++){
v.addElement (i);
}
Enumeration e = v.elements ();
while (e.hasMoreElements ()) {
Notes by vk

Integer I = (Interger) e.nextElement ();


If ((i%2) == 0 )
System.out.println (i);
}
System.out.println (v);
}
}
Limitations of Enumeration:
- Enumeration concept is applicable only for legacy
classes and hence it is not a universal cursor.
- By using Enumeration, we can get only access and we
can’t perform remove operation.
Note: - To overcome above limitations of Enumeration we
should go for Iterator.
b. Iterator
- We can apply Iterator concept for any Collection
object hence it is universal cursor.
- By using Iterator, we can perform both read and
remove operations.
- We can create Iterator, object by using iterator ()
method of Collection interface.
 public Iterator iterator ();
Ex…!
Iterator itr = c.iterator ();
- where c is any collection object
Methods in Iterator
- Iterator interface defines the following three methods
a. public boolean hasNext ()
Notes by vk

b. public Object next ()


c. public void remove ()

You might also like