Collection Framework
Collection Framework
To store multiple objects or group of objects together we can generally use arrays.
But arrays has some limitations
Limitations of Array :
1. The size of the array is fixed, we cannot reduce or increase dynamically during
the execution of the program.
2. Array is a collection of homogeneous elements.
3. Array manipulation such as :
1. removing an element from an array.
2. adding the element in between the array etc…
Requires complex logic to solve.
Therefore, to avoid the limitations of the array we can store the group of objects or
elements using different data structures such as :
1. List
2. Set
3. Queue
4. maps / dictionaries
Collection interface :
List interface:
ArrayList :
Collection Framework Page 6
ArrayList :
Note:
Constructors:
Note :
1. toString method is Overridden such that it returns a view of all the elements
present in the array list.
[ element1 , element2, … ] ….
Add(Object ) AddAll(Collection )
Note :
1. get method
2. iterator
3. ListIterator
4. for each loop
1. get(index ) :
java.util.Iterator :
Collection Framework Page 8
java.util.Iterator :
example :
example :
refer,
Disadvantage Of Iterator :
3. listIterator() :
ListIterator :
Methods of ListIterator :
example :
ls.listIterator( 2 ) ;
Example refer :
========================================================
syntax :
Note :
1. non-generic collection.
2. generic collection.
1. Non-Generic Collection :
Example refer :
2. Generic Collection :
Note :
To Sort an ArrayList :
We can sort the arraylist with the help of sort() method present in
Collections class
1. sort( arraylist ls )
2. sort( arraylist ls , comparator ref )
1. sort( arraylist ls ) :
workspace/collections/src/arraylist/sort/ StudentDriver1.java
workspace/collections/src/arraylist/sort/S4.java
=======================================================
Set :
Characteristics Of Set :
1. HashSet :
Characteristics :
1. It is unordered.
2. No Duplicates
3. No index
Constructors :
Methods:
2. TreeSet :
Characteristics :
Constructors :
Methods :
Maps :
Map is a data structure, which helps the programmers to store the data in the
form of key value pairs.
Note :
example:
HashMap :
It is a concrete implementing class of Map interface.
TreeMap :
HashTable :
=======================================================
Task :
=======================================================
Conversions :
3. ArrayList to TreeSet
4. TreeSet to ArrayList
5. Map to Set :
We can convert a Collection into an Array with the help of toArray() method
present in Collection interface.
Task2 :
input : array
task: convert array to Arraylist
return : ArrayList
====================================================
Note :