SlideShare a Scribd company logo
C ollection Framework
List Set Map Prepared By: Minal Maniar
Collection Framework
❏ The Java language supports fixed-size arrays to store data.
❏ Developer typically require a data structure which is flexible in size, so that they can
add and remove items from this data structure on request. To avoid that every
developer has to implement his custom data structure the Java library provide several
default implementations for this via the collection framework.
❏ The java.util package contains one of Java’s most powerful subsystems: collections.
❏ Collections were added by the initial release of Java 2, and enhanced by Java 2 – version
1.4.
❏ Java collections are dynamic in size, e.g. a collection can contain a flexible number of
objects.
Collection Hierarchy
Map Hierarchy
Iterator
Iterators provide a means of traversing a set of data. It can be used with arrays and
various classes in the Collection Framework. The Iterator interface supports the
following methods:
• next: This method returns the next element
• hasNext: This method returns true if there are additional elements
• remove: This method removes the element from the list
The ListIterator interface, when available, is an alternative to the Iterator
interface. It uses the same methods and provides additional capabilities including:
• Traversal of the list in either direction
• Modification of its elements
• Access to the element's position
ListIterator
The methods of the ListIterator interface include the following:
• next: This method returns the next element
• previous: This method returns the previous element
• hasNext: This method returns true if there are additional elements that follow the
current one
• hasPrevious: This method returns true if there are additional elements that
precede the current one
• nextIndex: This method returns the index of the next element to be returned
by the next method
• previousIndex: This method returns the index of the previous element to be
returned by the previous method
• add: This method inserts an element into the list (optional)
• remove: This method removes the element from the list (optional)
• set: This method replaces an element in the list (optional)
The List Interface
❏ The List Interface extends Collection and declares behavior of a collection that stores a
sequence of elements.
❏ Developer typically require a data structure which is flexible in size, so that they can
add and remove items from this data structure on request. To avoid that every
developer has to implement his custom data structure the Java library provide several
default implementations for this via the collection framework.
❏ The java.util package contains one of Java’s most powerful subsystems: collections.
❏ Collections were added by the initial release of Java 2, enhanced by Java2–version1.4
❏ Java collections are dynamic in size, e.g. a collection can contain a flexible number of
objects.
The ArrayList Class
What is unique feature of ArrayList?
❏ ArrayList in Java is most frequently used collection class after HashMap in Java.
❏ Java ArrayList represents an automatic re-sizeable array and used in place of array. Since we
can not modify size of an array after creating it, we prefer to use ArrayList in Java which
resize itself automatically once it gets full.
❏ It implements List interface and allow null not thread safe.
❏ Java ArrayList also maintains insertion order of elements and allows duplicates.
❏ ArrayList supports both Iterator and ListIterator for iteration but it’s recommended to use
ListIterator as it allows the programmer to traverse the list in either direction, modify the list
during iteration, and obtain the Iterator's current position in the list.
Creating ArrayList
The ArrayList class possesses the following three constructors:
• A default constructor
• One that accepts a Collection object
• One that accepts an initial capacity
The capacity of a ArrayList object refers to how many elements the list can hold.
When more elements need to be added and the list is full, the size of the list will be automatically
increased. The initial capacity of a ArrayList created with its default constructor is 10.
The following example creates 2 lists, one with a capacity of 10 and the second with a capacity of 20:
ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(20);
The ArrayList class supports generics. Here, a list of strings is created:
ArrayList<String> list3 = new ArrayList<String>();
Storage in ArrayList
❏ Internally, both the ArrayList hold onto their contents using an Array. An ArrayList defaults to
50% increase in the size of its array when it inserts last element of initial capacity,
❏ Ex: ArrayList al = new ArrayList();
50 1 32 4 76 98
Creates 10 array blocks initially
50 1 32 4 76 98 10 11 1312 14
At the time of inserting 10th element, 5
array blocks(50% of the size) is created, old
data is shifted to new ArrayList
ArrayList Example
Store Object in ArrayList
The Vector Class
What is unique feature of Vector?
❏ Vector is a Concrete class - ordered collection (add/remove elements at
the end) and implements dynamic resizable array. It is similar to ArrayList
but with few differences.
❏ Vectors are synchronized: Any method that touches the Vector's contents
is thread safe. This means if one thread is working on Vector, no other thread
can get a hold of it. Unlike ArrayList, only one thread can perform an
operation on vector at a time.
Storage in Vector
How do Vector stores Elements?
❏ Internally, both the ArrayList and Vector hold onto their contents using an Array. A Vector
defaults to doubling the size of its array when it inserts last element of initial capacity,
❏ Ex: Vector v = new Vector();
50 1 32 4 76 98
Creates 10 array blocks initially
50 1 32 4 76 98 1510 11 1312 14 1716 1918
At the time of inserting 10th element, 20
array blocks(doubling the size) is created,
old data is shifted to new Vector
Performance and Usage Pattern of Vector
❏ Vector are good for retrieving elements from a specific position in the container
or for adding and removing elements from the end of the container. All of these
operations can be performed in constant time - However, adding and removing
elements from any other position proves more expensive - Linear. These
operations are more expensive because you have to shift all elements at index i
and higher over by one element. So, if you want to index elements or add and
remove elements at the end of the array, use either a Vector or an ArrayList.
❏ It's always best to set the object's initial capacity to the largest capacity that your
program will need.
❏ By carefully setting the capacity, you can avoid paying the penalty needed to
resize the internal array later. If you don't know how much data you'll have, but
you do know the rate at which it grows, Vector does possess a slight advantage
since you can set the increment value.
Declare a Vector
3 ways to declare a Vector
1. Vector vec = new Vector(); // Creates Vector default size is 10.
2. Vector object= new Vector(int initialCapacity) // Creates Vector
with given initial capacity Ex: Vector vec = new Vector(3);
3. Vector object= new vector(int initialcapacity, capacityIncrement)
Ex: Vector vec= new Vector(4, 6)
Creates Vector with initial capacity of 4 and when inserts 4th
element, increments its size by 6. This will result into new Vector
of size 10.
Vector Example
Vector Example : Output
ArrayList vs Vector
Differences
1) Synchronization and Thread-safe: Vector is synchronized while ArrayList is not
synchronized. ArrayList is non-synchronized which means multiple threads can work on ArrayList at
the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an
another thread performing remove operation on ArrayList at the same time in a multithreaded
environment
while Vector is synchronized. This means if one thread is working on Vector, no other thread can
get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
ArrayList vs Vector(2)
2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal
use of storage, however the way they resized is different. ArrayList grow by half of its size (50%
increase) when resized while Vector doubles the size of itself by default when grows.
By default ArrayList size is 10. It checks whether it reaches to last element, then it will create a
new array, copy old array data to new one and old array will be eligible for garbage collection by
JVM.
3) Performance: Vector is slow as it is thread safe compared to ArrayList. ArrayList gives better
performance as it is non-synchronized. Vector operations gives poor performance as they are
thread-safe, the thread which works on Vector gets a lock on it which makes other thread wait till
the lock is released.
ArrayList vs Vector(3)
4) Set Increment Size: ArrayList does not define the increment size . Vector defines the
increment size .
You can find the following method in Vector Class.
public synchronized void setSize(int i) { //some code }. There is no setSize() method or any other
method in ArrayList which can manually set the increment size.
Similarities
1. Both Vector and ArrayList use growable array data structure.
2. The iterator and listIterator returned by these classes (Vector and ArrayList) are fail-fast.
3. They both are ordered collection classes as they maintain the elements insertion order.
4. Vector & ArrayList both allows duplicate and null values.
5. They both grows and shrinks automatically when overflow and deletion happens.
When to use ArrayList and when to use
Vector?
❏ It totally depends on the requirement. If there is a need to perform
“thread-safe” operation the vector is your best bet as it ensures that
only one thread access the collection at a time.
❏ Performance: Synchronized operations consumes more time compared to
non-synchronized ones so if there is no need for thread safe operation,
ArrayList is a better choice as performance will be improved because of
the concurrent processes.
Test performance by calculating Time
How to make ArrayList synchronized?
//Use Collecions.synzhonizedList method
List list = Collections.synchronizedList(new ArrayList());
...
//If you want to use iterator on the synchronized list, It should be in synchronized block.
synchronized (list) {
Iterator iterator = list.iterator();
while (iterator.hasNext())
...
iterator.next();
...
Exercise
1. Write a program that reads a text file, specified by the first command
line argument, into a List. The program should then print random
lines from the file, the number of lines printed to be specified by the
second command line argument. Write the program so that a
correctly-sized collection is allocated all at once, instead of being
gradually expanded as the file is read in. Hint: To determine the
number of lines in the file, use java.io.File.length to obtain the size of
the file, then divide by an assumed size of an average line.
(Refer document for the solution) Note : Refer document for 2 more exercise questions.
2. Write a program that adds 5 String elements in Vector print them in
forward and backward order. [Hint: for backward order use previous()
method of ListIterator.]
Assignment Questions
1. Array vs ArrayList
2. ArrayList vs Vector
3. How to copy or clone an ArrayList?
4. How to copy array to ArrayList?
5. How to shuffle elemenets in ArrayList?
6. How to read all elemenets in Vector by using iterator?
7. How to copy or clone a Vector?
8. How to add all elemenets of a list to Vector?
9. How to delete all elemenets from Vector?
10. How to find does Vector contains all list elemenets or not?
11. How to copy Vector to Array?
12. How to get sublist from Vector?
Hashing
● Hashing is a process of taking a big volume into small volume of data and to have strong
association between keys and values
● Short list is created from a long list in such way that it work as a long list was.
● Here short list will only contain sufficient information- not all info
L l
S s s < l
Hashing and Associative Array are similar
The Set Interface
What is unique feature of Set?
❏ Set is a collection interface - Collection that cannot contain duplicate
elements. (Ex. Set of playing cards)
❏ Set Implementations
● java.util.HashSet – Stores unique elements in Hash Table
● java.util.TreeSet - Stores unique elements in Hash Table in sorted order
(Ascending)
● java.util.LinkedHashSet - Stores unique elements in Hash Table and maintain
insertion order
● Note: Refer Set_Map.txt document (in shared folder of Google Drive) for Examples
of HashSet and TreeSet
MAP – Key value pair
The Map Interface
What is unique feature of Map?
● The java.util.Map interface represents a mapping between a key and a value
● The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of
the collection types.
❏ Map Implementations
● java.util.HashMap – Stores key valye pair
● java.util.Hashtable - Similar to HashMap, but sunchronized
● java.util.EnumMap - use enum values as keys for lookup
● java.util.IdentityHashMap - uses reference equality when comparing elements
● java.util.LinkedHashMap - maintains a linked list of the entries and in the order in which they were inserted
● java.util.TreeMap - provides an efficient means of storing key/value pairs in sorted order
● java.util.WeakHashMap - stores only weak references to its keys
❏ Most commonly used Map implementations are HashMap and TreeMap
❏ Note: Refer Set_Map.txt document (in shared folder of Google Drive) for Examples of HashSet and
TreeSet
References
❏ http://docs.oracle.com/
❏ http://www.tutorialspoint.com/
❏ http://javarevisited.blogspot.in/
❏ Oracle Certified Associate, Java SE 7 Programmer Study Guide by Richard M. Reese
❏ Java The Complete Reference by Herbert Schildt
Ad

More Related Content

What's hot (20)

Generics
GenericsGenerics
Generics
Ravi_Kant_Sahu
 
Collections In Java
Collections In JavaCollections In Java
Collections In Java
Binoj T E
 
Java Exception handling
Java Exception handlingJava Exception handling
Java Exception handling
kamal kotecha
 
Delegates and events in C#
Delegates and events in C#Delegates and events in C#
Delegates and events in C#
Dr.Neeraj Kumar Pandey
 
Vectors in Java
Vectors in JavaVectors in Java
Vectors in Java
Abhilash Nair
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
Raja Sekhar
 
Java Collections
Java CollectionsJava Collections
Java Collections
parag
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
Prof. Erwin Globio
 
Java/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBCJava/Servlet/JSP/JDBC
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
Arulmurugan Rajaraman
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
Lovely Professional University
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
Abhilash Nair
 
Collections - Lists, Sets
Collections - Lists, Sets Collections - Lists, Sets
Collections - Lists, Sets
Hitesh-Java
 
Type casting in java
Type casting in javaType casting in java
Type casting in java
Farooq Baloch
 
L11 array list
L11 array listL11 array list
L11 array list
teach4uin
 
Java annotations
Java annotationsJava annotations
Java annotations
FAROOK Samath
 

Viewers also liked (9)

3 interaction and_state_modeling
3 interaction and_state_modeling3 interaction and_state_modeling
3 interaction and_state_modeling
Minal Maniar
 
Class method object
Class method objectClass method object
Class method object
Minal Maniar
 
1 modeling concepts
1 modeling concepts1 modeling concepts
1 modeling concepts
Minal Maniar
 
Object oriented thinking
Object oriented thinkingObject oriented thinking
Object oriented thinking
Minal Maniar
 
Java8 features
Java8 featuresJava8 features
Java8 features
Minal Maniar
 
2 class use case
2 class use case2 class use case
2 class use case
Minal Maniar
 
Io
IoIo
Io
Minal Maniar
 
Multi t hreading_14_10
Multi t hreading_14_10Multi t hreading_14_10
Multi t hreading_14_10
Minal Maniar
 
4 sdlc
4 sdlc4 sdlc
4 sdlc
Minal Maniar
 
Ad

Similar to 5 collection framework (20)

Java Unit 2 (Part 2)
Java Unit 2 (Part 2)Java Unit 2 (Part 2)
Java Unit 2 (Part 2)
Dr. SURBHI SAROHA
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
Java collections notes
Java collections notesJava collections notes
Java collections notes
Surendar Meesala
 
VTUOOPMCA5THMODULECollection OverV .pptx
VTUOOPMCA5THMODULECollection OverV .pptxVTUOOPMCA5THMODULECollection OverV .pptx
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
mca5thCollection OverViCollection O.pptx
mca5thCollection OverViCollection O.pptxmca5thCollection OverViCollection O.pptx
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULECollection OverVi.pptx
VTUOOPMCA5THMODULECollection OverVi.pptxVTUOOPMCA5THMODULECollection OverVi.pptx
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULEvCollection OverV.pptx
VTUOOPMCA5THMODULEvCollection OverV.pptxVTUOOPMCA5THMODULEvCollection OverV.pptx
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
Java util
Java utilJava util
Java util
Srikrishna k
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Java collections
Java collectionsJava collections
Java collections
padmad2291
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
IllllBikkySharmaIlll
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 
Advanced core java
Advanced core javaAdvanced core java
Advanced core java
Rajeev Uppala
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
Lecture 9
Lecture 9Lecture 9
Lecture 9
talha ijaz
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
LOVELY PROFESSIONAL UNIVERSITY
 
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answeredU-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
U-III-part-1.pptxpart 1 of Java and hardware coding questions are answered
zainmkhan20
 
collection framework.pptx
collection framework.pptxcollection framework.pptx
collection framework.pptx
SoniaKapoor56
 
VTUOOPMCA5THMODULECollection OverV .pptx
VTUOOPMCA5THMODULECollection OverV .pptxVTUOOPMCA5THMODULECollection OverV .pptx
VTUOOPMCA5THMODULECollection OverV .pptx
VeenaNaik23
 
mca5thCollection OverViCollection O.pptx
mca5thCollection OverViCollection O.pptxmca5thCollection OverViCollection O.pptx
mca5thCollection OverViCollection O.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULECollection OverVi.pptx
VTUOOPMCA5THMODULECollection OverVi.pptxVTUOOPMCA5THMODULECollection OverVi.pptx
VTUOOPMCA5THMODULECollection OverVi.pptx
VeenaNaik23
 
VTUOOPMCA5THMODULEvCollection OverV.pptx
VTUOOPMCA5THMODULEvCollection OverV.pptxVTUOOPMCA5THMODULEvCollection OverV.pptx
VTUOOPMCA5THMODULEvCollection OverV.pptx
VeenaNaik23
 
Collection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshanCollection framework (completenotes) zeeshan
Collection framework (completenotes) zeeshan
Zeeshan Khan
 
Java collections
Java collectionsJava collections
Java collections
padmad2291
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
IllllBikkySharmaIlll
 
collectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptxcollectionsframework210616084411 (1).pptx
collectionsframework210616084411 (1).pptx
ArunPatrick2
 
List interface in collections framework
List interface in collections frameworkList interface in collections framework
List interface in collections framework
Ravi Chythanya
 
arraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylistarraylist in java a comparison of the array and arraylist
arraylist in java a comparison of the array and arraylist
PriyadharshiniG41
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
Krishna Sujeer
 
Ad

More from Minal Maniar (6)

Exception handling
Exception handlingException handling
Exception handling
Minal Maniar
 
Java ce241
Java ce241Java ce241
Java ce241
Minal Maniar
 
Java servlet technology
Java servlet technologyJava servlet technology
Java servlet technology
Minal Maniar
 
Oop java
Oop javaOop java
Oop java
Minal Maniar
 
modeling concepts
modeling conceptsmodeling concepts
modeling concepts
Minal Maniar
 
modeling concepts
modeling conceptsmodeling concepts
modeling concepts
Minal Maniar
 

Recently uploaded (20)

Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Structural Response of Reinforced Self-Compacting Concrete Deep Beam Using Fi...
Journal of Soft Computing in Civil Engineering
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Development of MLR, ANN and ANFIS Models for Estimation of PCUs at Different ...
Journal of Soft Computing in Civil Engineering
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Process Parameter Optimization for Minimizing Springback in Cold Drawing Proc...
Journal of Soft Computing in Civil Engineering
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 
Data Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptxData Structures_Introduction to algorithms.pptx
Data Structures_Introduction to algorithms.pptx
RushaliDeshmukh2
 
Compiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptxCompiler Design Unit1 PPT Phases of Compiler.pptx
Compiler Design Unit1 PPT Phases of Compiler.pptx
RushaliDeshmukh2
 
Smart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineeringSmart Storage Solutions.pptx for production engineering
Smart Storage Solutions.pptx for production engineering
rushikeshnavghare94
 
ELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdfELectronics Boards & Product Testing_Shiju.pdf
ELectronics Boards & Product Testing_Shiju.pdf
Shiju Jacob
 
Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.Fort night presentation new0903 pdf.pdf.
Fort night presentation new0903 pdf.pdf.
anuragmk56
 
Value Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous SecurityValue Stream Mapping Worskshops for Intelligent Continuous Security
Value Stream Mapping Worskshops for Intelligent Continuous Security
Marc Hornbeek
 
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdfMAQUINARIA MINAS CEMA 6th Edition (1).pdf
MAQUINARIA MINAS CEMA 6th Edition (1).pdf
ssuser562df4
 
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design ThinkingDT REPORT by Tech titan GROUP to introduce the subject design Thinking
DT REPORT by Tech titan GROUP to introduce the subject design Thinking
DhruvChotaliya2
 
Introduction to FLUID MECHANICS & KINEMATICS
Introduction to FLUID MECHANICS &  KINEMATICSIntroduction to FLUID MECHANICS &  KINEMATICS
Introduction to FLUID MECHANICS & KINEMATICS
narayanaswamygdas
 
15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...15th International Conference on Computer Science, Engineering and Applicatio...
15th International Conference on Computer Science, Engineering and Applicatio...
IJCSES Journal
 
Avnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights FlyerAvnet Silica's PCIM 2025 Highlights Flyer
Avnet Silica's PCIM 2025 Highlights Flyer
WillDavies22
 
Artificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptxArtificial Intelligence (AI) basics.pptx
Artificial Intelligence (AI) basics.pptx
aditichinar
 
Level 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical SafetyLevel 1-Safety.pptx Presentation of Electrical Safety
Level 1-Safety.pptx Presentation of Electrical Safety
JoseAlbertoCariasDel
 
International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)International Journal of Distributed and Parallel systems (IJDPS)
International Journal of Distributed and Parallel systems (IJDPS)
samueljackson3773
 
DSP and MV the Color image processing.ppt
DSP and MV the  Color image processing.pptDSP and MV the  Color image processing.ppt
DSP and MV the Color image processing.ppt
HafizAhamed8
 
introduction to machine learining for beginers
introduction to machine learining for beginersintroduction to machine learining for beginers
introduction to machine learining for beginers
JoydebSheet
 
Smart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptxSmart_Storage_Systems_Production_Engineering.pptx
Smart_Storage_Systems_Production_Engineering.pptx
rushikeshnavghare94
 

5 collection framework

  • 1. C ollection Framework List Set Map Prepared By: Minal Maniar
  • 2. Collection Framework ❏ The Java language supports fixed-size arrays to store data. ❏ Developer typically require a data structure which is flexible in size, so that they can add and remove items from this data structure on request. To avoid that every developer has to implement his custom data structure the Java library provide several default implementations for this via the collection framework. ❏ The java.util package contains one of Java’s most powerful subsystems: collections. ❏ Collections were added by the initial release of Java 2, and enhanced by Java 2 – version 1.4. ❏ Java collections are dynamic in size, e.g. a collection can contain a flexible number of objects.
  • 5. Iterator Iterators provide a means of traversing a set of data. It can be used with arrays and various classes in the Collection Framework. The Iterator interface supports the following methods: • next: This method returns the next element • hasNext: This method returns true if there are additional elements • remove: This method removes the element from the list The ListIterator interface, when available, is an alternative to the Iterator interface. It uses the same methods and provides additional capabilities including: • Traversal of the list in either direction • Modification of its elements • Access to the element's position
  • 6. ListIterator The methods of the ListIterator interface include the following: • next: This method returns the next element • previous: This method returns the previous element • hasNext: This method returns true if there are additional elements that follow the current one • hasPrevious: This method returns true if there are additional elements that precede the current one • nextIndex: This method returns the index of the next element to be returned by the next method • previousIndex: This method returns the index of the previous element to be returned by the previous method • add: This method inserts an element into the list (optional) • remove: This method removes the element from the list (optional) • set: This method replaces an element in the list (optional)
  • 7. The List Interface ❏ The List Interface extends Collection and declares behavior of a collection that stores a sequence of elements. ❏ Developer typically require a data structure which is flexible in size, so that they can add and remove items from this data structure on request. To avoid that every developer has to implement his custom data structure the Java library provide several default implementations for this via the collection framework. ❏ The java.util package contains one of Java’s most powerful subsystems: collections. ❏ Collections were added by the initial release of Java 2, enhanced by Java2–version1.4 ❏ Java collections are dynamic in size, e.g. a collection can contain a flexible number of objects.
  • 8. The ArrayList Class What is unique feature of ArrayList? ❏ ArrayList in Java is most frequently used collection class after HashMap in Java. ❏ Java ArrayList represents an automatic re-sizeable array and used in place of array. Since we can not modify size of an array after creating it, we prefer to use ArrayList in Java which resize itself automatically once it gets full. ❏ It implements List interface and allow null not thread safe. ❏ Java ArrayList also maintains insertion order of elements and allows duplicates. ❏ ArrayList supports both Iterator and ListIterator for iteration but it’s recommended to use ListIterator as it allows the programmer to traverse the list in either direction, modify the list during iteration, and obtain the Iterator's current position in the list.
  • 9. Creating ArrayList The ArrayList class possesses the following three constructors: • A default constructor • One that accepts a Collection object • One that accepts an initial capacity The capacity of a ArrayList object refers to how many elements the list can hold. When more elements need to be added and the list is full, the size of the list will be automatically increased. The initial capacity of a ArrayList created with its default constructor is 10. The following example creates 2 lists, one with a capacity of 10 and the second with a capacity of 20: ArrayList list1 = new ArrayList(); ArrayList list2 = new ArrayList(20); The ArrayList class supports generics. Here, a list of strings is created: ArrayList<String> list3 = new ArrayList<String>();
  • 10. Storage in ArrayList ❏ Internally, both the ArrayList hold onto their contents using an Array. An ArrayList defaults to 50% increase in the size of its array when it inserts last element of initial capacity, ❏ Ex: ArrayList al = new ArrayList(); 50 1 32 4 76 98 Creates 10 array blocks initially 50 1 32 4 76 98 10 11 1312 14 At the time of inserting 10th element, 5 array blocks(50% of the size) is created, old data is shifted to new ArrayList
  • 12. Store Object in ArrayList
  • 13. The Vector Class What is unique feature of Vector? ❏ Vector is a Concrete class - ordered collection (add/remove elements at the end) and implements dynamic resizable array. It is similar to ArrayList but with few differences. ❏ Vectors are synchronized: Any method that touches the Vector's contents is thread safe. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
  • 14. Storage in Vector How do Vector stores Elements? ❏ Internally, both the ArrayList and Vector hold onto their contents using an Array. A Vector defaults to doubling the size of its array when it inserts last element of initial capacity, ❏ Ex: Vector v = new Vector(); 50 1 32 4 76 98 Creates 10 array blocks initially 50 1 32 4 76 98 1510 11 1312 14 1716 1918 At the time of inserting 10th element, 20 array blocks(doubling the size) is created, old data is shifted to new Vector
  • 15. Performance and Usage Pattern of Vector ❏ Vector are good for retrieving elements from a specific position in the container or for adding and removing elements from the end of the container. All of these operations can be performed in constant time - However, adding and removing elements from any other position proves more expensive - Linear. These operations are more expensive because you have to shift all elements at index i and higher over by one element. So, if you want to index elements or add and remove elements at the end of the array, use either a Vector or an ArrayList. ❏ It's always best to set the object's initial capacity to the largest capacity that your program will need. ❏ By carefully setting the capacity, you can avoid paying the penalty needed to resize the internal array later. If you don't know how much data you'll have, but you do know the rate at which it grows, Vector does possess a slight advantage since you can set the increment value.
  • 16. Declare a Vector 3 ways to declare a Vector 1. Vector vec = new Vector(); // Creates Vector default size is 10. 2. Vector object= new Vector(int initialCapacity) // Creates Vector with given initial capacity Ex: Vector vec = new Vector(3); 3. Vector object= new vector(int initialcapacity, capacityIncrement) Ex: Vector vec= new Vector(4, 6) Creates Vector with initial capacity of 4 and when inserts 4th element, increments its size by 6. This will result into new Vector of size 10.
  • 19. ArrayList vs Vector Differences 1) Synchronization and Thread-safe: Vector is synchronized while ArrayList is not synchronized. ArrayList is non-synchronized which means multiple threads can work on ArrayList at the same time. For e.g. if one thread is performing an add operation on ArrayList, there can be an another thread performing remove operation on ArrayList at the same time in a multithreaded environment while Vector is synchronized. This means if one thread is working on Vector, no other thread can get a hold of it. Unlike ArrayList, only one thread can perform an operation on vector at a time.
  • 20. ArrayList vs Vector(2) 2) Resize: Both ArrayList and Vector can grow and shrink dynamically to maintain the optimal use of storage, however the way they resized is different. ArrayList grow by half of its size (50% increase) when resized while Vector doubles the size of itself by default when grows. By default ArrayList size is 10. It checks whether it reaches to last element, then it will create a new array, copy old array data to new one and old array will be eligible for garbage collection by JVM. 3) Performance: Vector is slow as it is thread safe compared to ArrayList. ArrayList gives better performance as it is non-synchronized. Vector operations gives poor performance as they are thread-safe, the thread which works on Vector gets a lock on it which makes other thread wait till the lock is released.
  • 21. ArrayList vs Vector(3) 4) Set Increment Size: ArrayList does not define the increment size . Vector defines the increment size . You can find the following method in Vector Class. public synchronized void setSize(int i) { //some code }. There is no setSize() method or any other method in ArrayList which can manually set the increment size. Similarities 1. Both Vector and ArrayList use growable array data structure. 2. The iterator and listIterator returned by these classes (Vector and ArrayList) are fail-fast. 3. They both are ordered collection classes as they maintain the elements insertion order. 4. Vector & ArrayList both allows duplicate and null values. 5. They both grows and shrinks automatically when overflow and deletion happens.
  • 22. When to use ArrayList and when to use Vector? ❏ It totally depends on the requirement. If there is a need to perform “thread-safe” operation the vector is your best bet as it ensures that only one thread access the collection at a time. ❏ Performance: Synchronized operations consumes more time compared to non-synchronized ones so if there is no need for thread safe operation, ArrayList is a better choice as performance will be improved because of the concurrent processes.
  • 23. Test performance by calculating Time
  • 24. How to make ArrayList synchronized? //Use Collecions.synzhonizedList method List list = Collections.synchronizedList(new ArrayList()); ... //If you want to use iterator on the synchronized list, It should be in synchronized block. synchronized (list) { Iterator iterator = list.iterator(); while (iterator.hasNext()) ... iterator.next(); ...
  • 25. Exercise 1. Write a program that reads a text file, specified by the first command line argument, into a List. The program should then print random lines from the file, the number of lines printed to be specified by the second command line argument. Write the program so that a correctly-sized collection is allocated all at once, instead of being gradually expanded as the file is read in. Hint: To determine the number of lines in the file, use java.io.File.length to obtain the size of the file, then divide by an assumed size of an average line. (Refer document for the solution) Note : Refer document for 2 more exercise questions. 2. Write a program that adds 5 String elements in Vector print them in forward and backward order. [Hint: for backward order use previous() method of ListIterator.]
  • 26. Assignment Questions 1. Array vs ArrayList 2. ArrayList vs Vector 3. How to copy or clone an ArrayList? 4. How to copy array to ArrayList? 5. How to shuffle elemenets in ArrayList? 6. How to read all elemenets in Vector by using iterator? 7. How to copy or clone a Vector? 8. How to add all elemenets of a list to Vector? 9. How to delete all elemenets from Vector? 10. How to find does Vector contains all list elemenets or not? 11. How to copy Vector to Array? 12. How to get sublist from Vector?
  • 27. Hashing ● Hashing is a process of taking a big volume into small volume of data and to have strong association between keys and values ● Short list is created from a long list in such way that it work as a long list was. ● Here short list will only contain sufficient information- not all info L l S s s < l
  • 28. Hashing and Associative Array are similar
  • 29. The Set Interface What is unique feature of Set? ❏ Set is a collection interface - Collection that cannot contain duplicate elements. (Ex. Set of playing cards) ❏ Set Implementations ● java.util.HashSet – Stores unique elements in Hash Table ● java.util.TreeSet - Stores unique elements in Hash Table in sorted order (Ascending) ● java.util.LinkedHashSet - Stores unique elements in Hash Table and maintain insertion order ● Note: Refer Set_Map.txt document (in shared folder of Google Drive) for Examples of HashSet and TreeSet
  • 30. MAP – Key value pair
  • 31. The Map Interface What is unique feature of Map? ● The java.util.Map interface represents a mapping between a key and a value ● The Map interface is not a subtype of the Collection interface. Therefore it behaves a bit different from the rest of the collection types. ❏ Map Implementations ● java.util.HashMap – Stores key valye pair ● java.util.Hashtable - Similar to HashMap, but sunchronized ● java.util.EnumMap - use enum values as keys for lookup ● java.util.IdentityHashMap - uses reference equality when comparing elements ● java.util.LinkedHashMap - maintains a linked list of the entries and in the order in which they were inserted ● java.util.TreeMap - provides an efficient means of storing key/value pairs in sorted order ● java.util.WeakHashMap - stores only weak references to its keys ❏ Most commonly used Map implementations are HashMap and TreeMap ❏ Note: Refer Set_Map.txt document (in shared folder of Google Drive) for Examples of HashSet and TreeSet
  • 32. References ❏ http://docs.oracle.com/ ❏ http://www.tutorialspoint.com/ ❏ http://javarevisited.blogspot.in/ ❏ Oracle Certified Associate, Java SE 7 Programmer Study Guide by Richard M. Reese ❏ Java The Complete Reference by Herbert Schildt