SlideShare a Scribd company logo
 Introduction
 Collections and iterators
 Linked list
 Array list
 Hash set
 Tree set
 Maps
 Collections framework
 Data structures can make a big difference in programming
⚫ Do you need to search quickly? Do you need to rapidly insert and remove element? ...
 The first version of Java was supplied with a very small set of classes
⚫ Vector, Stack, Hashtable, BitSet and Enumeration
⚫ Java needed a serious data structure library
 Without the complexity of C++ STL(Standard Template Library)
 With the benefit of «generic algorithms» of C++ STL
⚫ The collections framework satisfies those needs
 Java collection framework separates interfaces and implementations
⚫ It defines a set of interfaces that represents abstract data structures
⚫ Each interface is then implemented in different ways,
each with main focus on some aspects
 For example, fast insertion, fast search, fixed memory consumption, ...
⚫ Using interfaces, you can change the implementation
simply modifying a single statement
// ArrayList optimizes random access, LinkedList modification stmts
List<Integer> list = new ArrayList<>();
list = new LinkedList<>()
 The fundamental interface for collection is the
Collection interface
⚫ The add method adds an element ot the collection
 Returns true if the collection was changed by the addition
⚫ Iterators are used visit elements in the collection
 Implements the Iterator design pattern
public interface Collection<E> {
boolean add(E element);
Iterator<E> iterator();
// ...
}
public interface Iterator<E> {
E next();
boolean hasNext();
void remove();
}
 Using iterators we have decoupled a collection from the
traversing policies
⚫ The order in which elements are visited depends on the the collection
type
⚫ Using the next method the collection is visited one
element at time
 If the end of the collection is reached an
NoSuchElementException is thrown
⚫ Use the hasNext method to check if the collection
has more elements to visit
⚫ Think of Java iterators as being between elements
 The iterator jumps over the next element
Think of Java iterators as being
between elements
While moving, the iterator returns
the current element
 Using next and hasNext it is possibile to
traverse the collection
⚫ As of Java 5, there is an elegant shortcut to looping a
collection using iterators
⚫ To use the for each loop the data structure must
implement Iterable<E> interface
for (String element : c) {
// do something with element
}
Collection<String> c = /* ... */;
Iterator<String> iter = c.iterator();
while (iter.hasNext()) {
String element = iter.next();
// do something with element
}
 Using an iterator it possibile to remove elements
from a collection
⚫ The remove method removes the element that was
returned by the last call to next
 There is a strong dependency between next and remove: it
is illegal to call remove if it wasn’t preceded by a call to next
⚫ This is the only way to safely modify a collection after
the creation of an iterator
for (Iterator<String> iterator = list.iterator();
iterator.hasNext();) {
// Point the iterator to the current element
String string = iterator.next();
iterator.remove();
}
 All concrete collections implement Collection
or Map interfaces
⚫ We will introduce only few of them
Collection type Description
ArrayList An indexed sequence that grows and
shrinks dynamically
LinkedList An ordered sequence that allows efficient
insertion and removal at any location
HashSet An unordered collection that rejects
duplicates
TreeSet A sorted set
HashMap A data structure that stores key/value
associations
 A LinkedList<E> is an ordered data structure
that stores each object in a link
⚫ Each link store a reference to the next link of the seq.
 In Java, a linked list is always doubly linked
Implements List<E>
interface
 Very efficient for remove and add operations
⚫ These ops are made through an Iterator
 Other elements in the list have not to be repositioned after
removal of an element
 Also di add operation is made efficiently
through an iterator of type ListIterator<E>
⚫ Use List.listIterator method to get one
⚫ New element is added before the current position of
the iterator
 Be carefull of concurrent modification using iterators
 Linked list are very inefficient in random access
interface ListIterator<E> extends Iterator<E> {
void add(E element);
E previous()
boolean hasPrevious()
}
for (int i = 0; i < list.size(); i++)
// do something with list.get(i);
Adding a new element
changes at most two
references
 An ArrayList<E> is an ordered data structure
that is very efficient in random access ops.
⚫ It encapsulate a dynamically reallocated array of
objects
⚫ Adding and removing operation
are not so efficient
 Reallocation of elements is needed
⚫ Use ArrayList instead of Vector
 More efficient due to its not
synchronized methods
 A Set<E> is a data structure that doesn’t care
about element’s ordering
⚫ A set contain the same element only once
⚫ Search operation performs very efficiently
⚫ A set is a Collection
 An HashSet<E> uses hash codes to distinguish
among elements
⚫ An hashCode is a number that can be derived from
object data
 You must provide an hash function to your classes
 The function must be compatible with the equals method
If the hash function produceds values
that are randomly distributed, collision
should be rare
buckets
 An HashSet is implemented using an hash table
⚫ The contains method is very efficient, because it has
to lookup the element only in one bucket
⚫ An iterator to hash set visit each bucket in turn
 Because of scattering, they are visited in a seemingly random
order
⚫ The add method adds an element if it is not already
present
 Don’t mutate an element in a set once inserted
⚫ If the hash code of an element were to change, the
element would no longer be in the correct position
 A TreeSet<E> is a sorted set
⚫ While iterating over the collection, the elements are
presented in sorted order
⚫ It uses a red-black tree to store data
 Insertion is slower than insertion in an hash table, but it is
still much faster than insertion in an array or linked list
 ...but a tree set automatically sorts the elements ;)
⚫ The type of the elements may implement
Comparable<T>
public interface Comparable<T> {
// It returns a value that is < 0, = 0 or > 0
int compareTo(T other);
}
 What if elements do not implement Comparable
or if you need more than on compation alg?
⚫ Provide a Comparator during set construction
 The compare method acts like the compareTo method
 Function object (lambda anyone?!)
 Using an HashSet or a TreeSet?
⚫ There must be a total ordering defined on elements
 You have to implement also the Comparator interface
⚫ Do you neeed elements to be sorted?
public interface Comparator<T> {
// Defines how two elements of type T have to be compared
int compare(T a, T b);
}
 A Map<K,V> is a data structure that allows you
to search an element using a key
⚫ A map stores key/value pairs
 Key must be unique: If you call the put method twice with
the same key, the second value replaces the first one.
 If no info is associated with a key, get returns null
 In sets to find an element you must have a copy of it
⚫ An HashMap hashes the keys
// HashMap implements Map
Map<String, Employee> staff = new HashMap<>();
Employee harry = new Employee("Harry Hacker");
staff.put("987-98-9996", harry);
String s = "987-98-9996";
e = staff.get(s); // gets harry
 The collection framework does not consider a
map itself as a Collection
⚫ It is possible to obtain views of the map
 If you are interested in all the values of a map, loop over the
enumeration of its entries
 Iterators on views cannot add elements to the map
 An UnsupportedOperationException is thrown
Set<K> keySet() // Set of keys
Collection<K> values() // Collection of values
Set<Map.Entry<K, V>> entrySet() // Set of pairs (key,value)
for (Map.Entry<String, Employee> entry : staff.entrySet()) {
String key = entry.getKey();
Employee value = entry.getValue();
// do something with key, value
}
 A framework is a set of classes that form the
basis for building advanced functionality
⚫ The Collection framework defines classes to
implement collections
⚫ The main interfaces are Collection and Map
 Insertion interfaces are different between the two types
 To get the elements from a Collection, just iterate over it
 To get a value from a Map, use the get method
// To insert an element in a Collection
boolean add(E element)
// To store a key/value pair in a Map
V put(K key, V value)
V get(K key)
 A List is an ordered collection
⚫ There is the concept of position of an element
 A list provides random access methods
 Lists provides a specialized iterator, ListIterator
 A Set is a Collection with no duplicates
⚫ The add method can reject a value if already present
⚫ Methods equals and hashCode are used to maintain
elements inside the set
void add(int index, E element)
E get(int index)
void remove(int index)
void add(E element)
 The framework provides some wrappers
 The framework have some companion objects
⚫ The Arrays type allows to trasform arrays into List
 And so on...
static <T> List<T> asList(T... a)
 The list returned is a view on the array: it is not possible to
change the size of the list; elements are the same
⚫ The Collections type have a bunch of utilities
 The method nCopies builds an illusory immutable list
List<String> settings = Collections.nCopies(100, "DEFAULT");
 Object is stored only once
 Method singleton returns an illusory set with one element
Collections.singleton(anObject)
EXAMPLES
https://beginnersbook.com/java-collections-tutorials/
LJ_JAVA_FS_Collection.pptx

More Related Content

Similar to LJ_JAVA_FS_Collection.pptx

Java collections
Java collectionsJava collections
Java collections
Hamid Ghorbani
 
collections
collectionscollections
collections
javeed_mhd
 
Java.util
Java.utilJava.util
Java.util
Ramakrishna kapa
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
Sony India Software Center
 
Collection framework
Collection frameworkCollection framework
Collection framework
DilvarSingh2
 
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 Collections
Java CollectionsJava Collections
Java Collectionsparag
 
Number 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdfNumber 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdf
advancethchnologies
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
Shalabh Chaudhary
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questionsyearninginjava
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
Ranjith Alappadan
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
bhawna sharma
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
Rajitha Reddy Alugati
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
RatnaJava
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
Nguync91368
 
Collection in Java
Collection in JavaCollection in Java
Collection in Java
Home
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
ManojKandhasamy1
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
mdfkhan625
 

Similar to LJ_JAVA_FS_Collection.pptx (20)

Java collections
Java collectionsJava collections
Java collections
 
collections
collectionscollections
collections
 
Java.util
Java.utilJava.util
Java.util
 
Java Collections Framework
Java Collections FrameworkJava Collections Framework
Java Collections Framework
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Nature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptxNature Activities Binder _ by Slidesgo.pptx
Nature Activities Binder _ by Slidesgo.pptx
 
Java Collections
Java CollectionsJava Collections
Java Collections
 
Number 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdfNumber 1 I have completed and number 6 is just uploading I .pdf
Number 1 I have completed and number 6 is just uploading I .pdf
 
Collections in Java Notes
Collections in Java NotesCollections in Java Notes
Collections in Java Notes
 
Java collections-interview-questions
Java collections-interview-questionsJava collections-interview-questions
Java collections-interview-questions
 
JAVA Collections frame work ppt
 JAVA Collections frame work ppt JAVA Collections frame work ppt
JAVA Collections frame work ppt
 
Collections lecture 35 40
Collections lecture 35 40Collections lecture 35 40
Collections lecture 35 40
 
TSAT Presentation1.pptx
TSAT Presentation1.pptxTSAT Presentation1.pptx
TSAT Presentation1.pptx
 
Collections - Lists & sets
Collections - Lists & setsCollections - Lists & sets
Collections - Lists & sets
 
1 list datastructures
1 list datastructures1 list datastructures
1 list datastructures
 
Md08 collection api
Md08 collection apiMd08 collection api
Md08 collection api
 
Collection in Java
Collection in JavaCollection in Java
Collection in Java
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Collection framework
Collection frameworkCollection framework
Collection framework
 

Recently uploaded

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
IES VE
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
rickgrimesss22
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
informapgpstrackings
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
Srikant77
 

Recently uploaded (20)

Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024Globus Compute wth IRI Workflows - GlobusWorld 2024
Globus Compute wth IRI Workflows - GlobusWorld 2024
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
Using IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New ZealandUsing IESVE for Room Loads Analysis - Australia & New Zealand
Using IESVE for Room Loads Analysis - Australia & New Zealand
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptxTop Features to Include in Your Winzo Clone App for Business Growth (4).pptx
Top Features to Include in Your Winzo Clone App for Business Growth (4).pptx
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
Field Employee Tracking System| MiTrack App| Best Employee Tracking Solution|...
 
RISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent EnterpriseRISE with SAP and Journey to the Intelligent Enterprise
RISE with SAP and Journey to the Intelligent Enterprise
 

LJ_JAVA_FS_Collection.pptx

  • 1.
  • 2.
  • 3.  Introduction  Collections and iterators  Linked list  Array list  Hash set  Tree set  Maps  Collections framework
  • 4.  Data structures can make a big difference in programming ⚫ Do you need to search quickly? Do you need to rapidly insert and remove element? ...  The first version of Java was supplied with a very small set of classes ⚫ Vector, Stack, Hashtable, BitSet and Enumeration ⚫ Java needed a serious data structure library  Without the complexity of C++ STL(Standard Template Library)  With the benefit of «generic algorithms» of C++ STL ⚫ The collections framework satisfies those needs
  • 5.  Java collection framework separates interfaces and implementations ⚫ It defines a set of interfaces that represents abstract data structures ⚫ Each interface is then implemented in different ways, each with main focus on some aspects  For example, fast insertion, fast search, fixed memory consumption, ... ⚫ Using interfaces, you can change the implementation simply modifying a single statement // ArrayList optimizes random access, LinkedList modification stmts List<Integer> list = new ArrayList<>(); list = new LinkedList<>()
  • 6.
  • 7.  The fundamental interface for collection is the Collection interface ⚫ The add method adds an element ot the collection  Returns true if the collection was changed by the addition ⚫ Iterators are used visit elements in the collection  Implements the Iterator design pattern public interface Collection<E> { boolean add(E element); Iterator<E> iterator(); // ... } public interface Iterator<E> { E next(); boolean hasNext(); void remove(); }
  • 8.  Using iterators we have decoupled a collection from the traversing policies ⚫ The order in which elements are visited depends on the the collection type ⚫ Using the next method the collection is visited one element at time  If the end of the collection is reached an NoSuchElementException is thrown ⚫ Use the hasNext method to check if the collection has more elements to visit ⚫ Think of Java iterators as being between elements  The iterator jumps over the next element
  • 9. Think of Java iterators as being between elements While moving, the iterator returns the current element
  • 10.  Using next and hasNext it is possibile to traverse the collection ⚫ As of Java 5, there is an elegant shortcut to looping a collection using iterators ⚫ To use the for each loop the data structure must implement Iterable<E> interface for (String element : c) { // do something with element } Collection<String> c = /* ... */; Iterator<String> iter = c.iterator(); while (iter.hasNext()) { String element = iter.next(); // do something with element }
  • 11.  Using an iterator it possibile to remove elements from a collection ⚫ The remove method removes the element that was returned by the last call to next  There is a strong dependency between next and remove: it is illegal to call remove if it wasn’t preceded by a call to next ⚫ This is the only way to safely modify a collection after the creation of an iterator for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { // Point the iterator to the current element String string = iterator.next(); iterator.remove(); }
  • 12.  All concrete collections implement Collection or Map interfaces ⚫ We will introduce only few of them Collection type Description ArrayList An indexed sequence that grows and shrinks dynamically LinkedList An ordered sequence that allows efficient insertion and removal at any location HashSet An unordered collection that rejects duplicates TreeSet A sorted set HashMap A data structure that stores key/value associations
  • 13.  A LinkedList<E> is an ordered data structure that stores each object in a link ⚫ Each link store a reference to the next link of the seq.  In Java, a linked list is always doubly linked Implements List<E> interface
  • 14.  Very efficient for remove and add operations ⚫ These ops are made through an Iterator  Other elements in the list have not to be repositioned after removal of an element
  • 15.  Also di add operation is made efficiently through an iterator of type ListIterator<E> ⚫ Use List.listIterator method to get one ⚫ New element is added before the current position of the iterator  Be carefull of concurrent modification using iterators  Linked list are very inefficient in random access interface ListIterator<E> extends Iterator<E> { void add(E element); E previous() boolean hasPrevious() } for (int i = 0; i < list.size(); i++) // do something with list.get(i);
  • 16. Adding a new element changes at most two references
  • 17.  An ArrayList<E> is an ordered data structure that is very efficient in random access ops. ⚫ It encapsulate a dynamically reallocated array of objects ⚫ Adding and removing operation are not so efficient  Reallocation of elements is needed ⚫ Use ArrayList instead of Vector  More efficient due to its not synchronized methods
  • 18.
  • 19.  A Set<E> is a data structure that doesn’t care about element’s ordering ⚫ A set contain the same element only once ⚫ Search operation performs very efficiently ⚫ A set is a Collection  An HashSet<E> uses hash codes to distinguish among elements ⚫ An hashCode is a number that can be derived from object data  You must provide an hash function to your classes  The function must be compatible with the equals method
  • 20. If the hash function produceds values that are randomly distributed, collision should be rare buckets
  • 21.  An HashSet is implemented using an hash table ⚫ The contains method is very efficient, because it has to lookup the element only in one bucket ⚫ An iterator to hash set visit each bucket in turn  Because of scattering, they are visited in a seemingly random order ⚫ The add method adds an element if it is not already present  Don’t mutate an element in a set once inserted ⚫ If the hash code of an element were to change, the element would no longer be in the correct position
  • 22.  A TreeSet<E> is a sorted set ⚫ While iterating over the collection, the elements are presented in sorted order ⚫ It uses a red-black tree to store data  Insertion is slower than insertion in an hash table, but it is still much faster than insertion in an array or linked list  ...but a tree set automatically sorts the elements ;) ⚫ The type of the elements may implement Comparable<T> public interface Comparable<T> { // It returns a value that is < 0, = 0 or > 0 int compareTo(T other); }
  • 23.  What if elements do not implement Comparable or if you need more than on compation alg? ⚫ Provide a Comparator during set construction  The compare method acts like the compareTo method  Function object (lambda anyone?!)  Using an HashSet or a TreeSet? ⚫ There must be a total ordering defined on elements  You have to implement also the Comparator interface ⚫ Do you neeed elements to be sorted? public interface Comparator<T> { // Defines how two elements of type T have to be compared int compare(T a, T b); }
  • 24.
  • 25.  A Map<K,V> is a data structure that allows you to search an element using a key ⚫ A map stores key/value pairs  Key must be unique: If you call the put method twice with the same key, the second value replaces the first one.  If no info is associated with a key, get returns null  In sets to find an element you must have a copy of it ⚫ An HashMap hashes the keys // HashMap implements Map Map<String, Employee> staff = new HashMap<>(); Employee harry = new Employee("Harry Hacker"); staff.put("987-98-9996", harry); String s = "987-98-9996"; e = staff.get(s); // gets harry
  • 26.  The collection framework does not consider a map itself as a Collection ⚫ It is possible to obtain views of the map  If you are interested in all the values of a map, loop over the enumeration of its entries  Iterators on views cannot add elements to the map  An UnsupportedOperationException is thrown Set<K> keySet() // Set of keys Collection<K> values() // Collection of values Set<Map.Entry<K, V>> entrySet() // Set of pairs (key,value) for (Map.Entry<String, Employee> entry : staff.entrySet()) { String key = entry.getKey(); Employee value = entry.getValue(); // do something with key, value }
  • 27.  A framework is a set of classes that form the basis for building advanced functionality ⚫ The Collection framework defines classes to implement collections ⚫ The main interfaces are Collection and Map  Insertion interfaces are different between the two types  To get the elements from a Collection, just iterate over it  To get a value from a Map, use the get method // To insert an element in a Collection boolean add(E element) // To store a key/value pair in a Map V put(K key, V value) V get(K key)
  • 28.  A List is an ordered collection ⚫ There is the concept of position of an element  A list provides random access methods  Lists provides a specialized iterator, ListIterator  A Set is a Collection with no duplicates ⚫ The add method can reject a value if already present ⚫ Methods equals and hashCode are used to maintain elements inside the set void add(int index, E element) E get(int index) void remove(int index) void add(E element)
  • 29.  The framework provides some wrappers
  • 30.  The framework have some companion objects ⚫ The Arrays type allows to trasform arrays into List  And so on... static <T> List<T> asList(T... a)  The list returned is a view on the array: it is not possible to change the size of the list; elements are the same ⚫ The Collections type have a bunch of utilities  The method nCopies builds an illusory immutable list List<String> settings = Collections.nCopies(100, "DEFAULT");  Object is stored only once  Method singleton returns an illusory set with one element Collections.singleton(anObject)
  • 31.