SlideShare a Scribd company logo
1 of 7
Chapitre 3
Les collections
Mouna Torjmen Khemakhem
Introduction
• Collection :
objet qui regroupe de multiples éléments dans une seule entité.
• Utilisation de collections pour
- stocker, retrouver et manipuler des données
- transmettre des données d ’une méthode à une autre
• Par exemple, un tableau est une collection
2
• Par exemple, un tableau est une collection
• Le JDK fournit d’autres types de collections sous la forme de classes et
d’interfaces
• Ces classes et interfaces sont dans le paquetage java.util
•Avant le JDK 5.0, les collections peuvent contenir des objets de n’importe quel
type
• A partir du JDK 5.0, on peut indiquer le type des objets contenus dans une
collection grâce à la généricitéMouna Torjmen Khemakhem
Types de collections
2 hiérarchies principales :
- Collection<E>
- Map<K,V>
• Map correspond aux collections indexées par des clés:
un élément de type V d’une map est retrouvé
rapidement si on connaît sa clé de type Krapidement si on connaît sa clé de type K
3
Mouna Torjmen Khemakhem
• Une classe exemple de Collection: ArrayList
import java.util.ArrayList;
• Une classe exemple de Map: HashMap
import java.util.HashMap;
ArrayList
import java.util.ArrayList;
import java.util.Arrays;
public class ArrayListTest {
public static void main(String args[])
ArrayList<String> list = new ArrayList<String>();
//add
list.add("Apple");
list.add("Google");
list.add("Samsung");
list.add("Microsoft");
//checking if ArrayList is empty
System.out.println(« Empty ? " +
list.isEmpty());
// removing an Object from ArrayList
System.out.println(« Before removing : " +
list);
list.remove(3); //removing fourth object
System.out.println("after removing : " + list);
// finding index of Object in List
System.out.println("What is index of Apple: "list.add("Microsoft");
//contains: use of equals method
System.out.println("Does list contains Apple :" +
list.contains("Apple"));
System.out.println("Does list contains Verizon :" +
list.contains("Verizon"));
// size
System.out.println("Size of ArrayList is : " +
list.size());
// replacing an object
System.out.println("before updating : " + list);
list.set(3, "Bank of America");
System.out.println("after update : " + list);
}
System.out.println("What is index of Apple: "
+ list.indexOf("Apple"));
// converting List to Array
String[] array = list.toArray(new String[]{});
System.out.println("Array from ArrayList : " +
Arrays.toString(array));
// removing all elements
list.clear();
System.out.println("Size of ArrayList after
clear : " + list.size());
}
4
Mouna Torjmen Khemakhem
Output ArrayList
/*
Does list contains Apple :true
Does list contains Verizon :false
Size of ArrayList is : 4
list before updating : [Apple, Google, Samsung, Microsoft]
list after update : [Apple, Google, Samsung, Bank of America]list after update : [Apple, Google, Samsung, Bank of America]
Does this ArrayList is empty : false
ArrayList before removing element : [Apple, Google, Samsung, Bank of
America]
ArrayList after removing element : [Apple, Google, Samsung]
What is index of Apple in this list : 0
Array from ArrayList : [Apple, Google, Samsung]
Size of ArrayList after clear : 0
*/
http://java67.blogspot.com/2012/11/java-arraylist-example-contains-add-set.htmlMouna Torjmen Khemakhem
HashMap
import java.util.HashMap;
import java.util.Iterator;
public class HashMapExample{
public static void main(String args[]){
HashMap hashMap = new HashMap();
// adding value into HashMap
hashMap.put("One", new Integer(1));
hashMap.put("Two", new Integer(2));
hashMap.put("Three", new Integer(3));
System.out.println("HashMap size" + hashMap.size() );
Integer one = (Integer) hashMap.get("One");
System.out.println("Value mapped with key
"One" is " + one);
System.out.println("Retrieving all keys ");
Iterator iterator = hashMap.keySet().iterator();
while(iterator. hasNext()){
System.out.println(iterator.next());
}
if(hashMap.containsValue(new Integer(1))){
System.out.println("HashMap contains 1 as value");
}else{
System.out.println("HashMap does not contain 1 as
value");
}
if( hashMap.containsKey("One") ){
System.out.println("HashMap contains One as key");
}else{
System.out.println("HashMap does not contain One
as value");
}
}
System.out.println("Retrieving all values ");
iterator = hashMap.entrySet().iterator();
while(iterator. hasNext()){
System.out.println(iterator.next());
}
System.out.println( hashMap.remove("One") + "
is removed from the HashMap.");
}
}
6
Mouna Torjmen Khemakhem
Output HashMap
/*
OUTPUT of the above given Java HashMap Example would be :
HashMap contains 3 key value pair.
HashMap contains 1 as value
HashMap contains One as key
Value mapped with key "One" is 1
Retrieving all keys from the HashMapRetrieving all keys from the HashMap
Three
Two
One
Retrieving all values from the HashMap
Three=3
Two=2
One=1
1 is removed from the HashMap.
*/
http://www.javadeveloper.co.in/java-example/java-hashmap-example.htmlMouna Torjmen Khemakhem

More Related Content

What's hot

Chap 6 : classes et interfaces
Chap 6 : classes et interfacesChap 6 : classes et interfaces
Chap 6 : classes et interfacesAziz Darouichi
 
Chapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaChapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaAziz Darouichi
 
Chapitre 5 classes abstraites et interfaces
Chapitre 5  classes abstraites et interfacesChapitre 5  classes abstraites et interfaces
Chapitre 5 classes abstraites et interfacesAmir Souissi
 
Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Aziz Darouichi
 
Correction Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfCorrection Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfslimyaich3
 
Exercice 1 java Héritage
Exercice 1 java HéritageExercice 1 java Héritage
Exercice 1 java HéritageNadaBenLatifa
 
Java cours n° 2 - classe-objet-constructeur
Java   cours n° 2 - classe-objet-constructeurJava   cours n° 2 - classe-objet-constructeur
Java cours n° 2 - classe-objet-constructeurAbdelwahab Naji
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateursAziz Darouichi
 
Cours algorithmique et complexite complet
Cours algorithmique et complexite completCours algorithmique et complexite complet
Cours algorithmique et complexite completChahrawoods Dmz
 
Chapitre5: Classes et objets
Chapitre5: Classes et objetsChapitre5: Classes et objets
Chapitre5: Classes et objetsAziz Darouichi
 
Chapitre 11: Expression Lambda et Référence de méthode en Java
Chapitre 11: Expression Lambda et Référence de méthode en JavaChapitre 11: Expression Lambda et Référence de méthode en Java
Chapitre 11: Expression Lambda et Référence de méthode en JavaAziz Darouichi
 
Héritage et polymorphisme- Jihen HEDHLI
Héritage et polymorphisme- Jihen HEDHLIHéritage et polymorphisme- Jihen HEDHLI
Héritage et polymorphisme- Jihen HEDHLIJihenHedhli1
 

What's hot (20)

Chap 6 : classes et interfaces
Chap 6 : classes et interfacesChap 6 : classes et interfaces
Chap 6 : classes et interfaces
 
Chapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En JavaChapitre8: Collections et Enumerations En Java
Chapitre8: Collections et Enumerations En Java
 
Chapitre 5 classes abstraites et interfaces
Chapitre 5  classes abstraites et interfacesChapitre 5  classes abstraites et interfaces
Chapitre 5 classes abstraites et interfaces
 
Polymorphisme (cours, résumé)
Polymorphisme (cours, résumé)Polymorphisme (cours, résumé)
Polymorphisme (cours, résumé)
 
Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références Chapitre4: Pointeurs et références
Chapitre4: Pointeurs et références
 
Correction Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdfCorrection Examen 2016-2017 POO .pdf
Correction Examen 2016-2017 POO .pdf
 
Exercice 1 java Héritage
Exercice 1 java HéritageExercice 1 java Héritage
Exercice 1 java Héritage
 
Polymorphisme, interface et classe abstraite
Polymorphisme, interface et classe abstraitePolymorphisme, interface et classe abstraite
Polymorphisme, interface et classe abstraite
 
Corrige tp java
Corrige tp javaCorrige tp java
Corrige tp java
 
Java cours n° 2 - classe-objet-constructeur
Java   cours n° 2 - classe-objet-constructeurJava   cours n° 2 - classe-objet-constructeur
Java cours n° 2 - classe-objet-constructeur
 
Chapitre6: Surcharge des opérateurs
Chapitre6:  Surcharge des opérateursChapitre6:  Surcharge des opérateurs
Chapitre6: Surcharge des opérateurs
 
Cours algorithmique et complexite complet
Cours algorithmique et complexite completCours algorithmique et complexite complet
Cours algorithmique et complexite complet
 
Chapitre5: Classes et objets
Chapitre5: Classes et objetsChapitre5: Classes et objets
Chapitre5: Classes et objets
 
Algorithmes de tri
Algorithmes de triAlgorithmes de tri
Algorithmes de tri
 
Ch 01 poo
Ch 01 pooCh 01 poo
Ch 01 poo
 
Chapitre 11: Expression Lambda et Référence de méthode en Java
Chapitre 11: Expression Lambda et Référence de méthode en JavaChapitre 11: Expression Lambda et Référence de méthode en Java
Chapitre 11: Expression Lambda et Référence de méthode en Java
 
TP C++ : Correction
TP C++ : CorrectionTP C++ : Correction
TP C++ : Correction
 
Cours java
Cours javaCours java
Cours java
 
TP C++ : enoncé
TP C++ : enoncéTP C++ : enoncé
TP C++ : enoncé
 
Héritage et polymorphisme- Jihen HEDHLI
Héritage et polymorphisme- Jihen HEDHLIHéritage et polymorphisme- Jihen HEDHLI
Héritage et polymorphisme- Jihen HEDHLI
 

Similar to POO Java Chapitre 3 Collections

Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Aijaz Ali Abro
 
collection framework in java
collection framework in javacollection framework in java
collection framework in javaMANOJ KUMAR
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_FrameworkKrishna Sujeer
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxrangariprajwal4554
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.pptYonas D. Ebren
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsSyed Afaq Shah MACS CP
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using Ccpjcollege
 
Collections generic
Collections genericCollections generic
Collections genericsandhish
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfarpitaeron555
 

Similar to POO Java Chapitre 3 Collections (20)

Collections framework
Collections frameworkCollections framework
Collections framework
 
STRINGS IN JAVA
STRINGS IN JAVASTRINGS IN JAVA
STRINGS IN JAVA
 
Collections and its types in C# (with examples)
Collections and its types in C# (with examples)Collections and its types in C# (with examples)
Collections and its types in C# (with examples)
 
collection framework in java
collection framework in javacollection framework in java
collection framework in java
 
12_-_Collections_Framework
12_-_Collections_Framework12_-_Collections_Framework
12_-_Collections_Framework
 
Java Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptxJava Programming Comprehensive Guide.pptx
Java Programming Comprehensive Guide.pptx
 
02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt02._Object-Oriented_Programming_Concepts.ppt
02._Object-Oriented_Programming_Concepts.ppt
 
Lecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and CollectionsLecture 4 - Object Interaction and Collections
Lecture 4 - Object Interaction and Collections
 
Java Collections Tutorials
Java Collections TutorialsJava Collections Tutorials
Java Collections Tutorials
 
Collection Framework-1.pptx
Collection Framework-1.pptxCollection Framework-1.pptx
Collection Framework-1.pptx
 
Data Structure Using C
Data Structure Using CData Structure Using C
Data Structure Using C
 
Core & advanced java classes in mumbai
Core & advanced java classes in mumbaiCore & advanced java classes in mumbai
Core & advanced java classes in mumbai
 
Lists
ListsLists
Lists
 
javacollections.pdf
javacollections.pdfjavacollections.pdf
javacollections.pdf
 
Collections (1)
Collections (1)Collections (1)
Collections (1)
 
Collections generic
Collections genericCollections generic
Collections generic
 
Python for Beginners
Python  for BeginnersPython  for Beginners
Python for Beginners
 
Lab Manual-OOP.pdf
Lab Manual-OOP.pdfLab Manual-OOP.pdf
Lab Manual-OOP.pdf
 
Introduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdfIntroduction and BackgroundIn recent lectures we discussed usi.pdf
Introduction and BackgroundIn recent lectures we discussed usi.pdf
 
C# Collection classes
C# Collection classesC# Collection classes
C# Collection classes
 

More from Mouna Torjmen

More from Mouna Torjmen (6)

TIC & E-Learning
TIC & E-LearningTIC & E-Learning
TIC & E-Learning
 
Apprentissage Par Projet APP
Apprentissage Par Projet APPApprentissage Par Projet APP
Apprentissage Par Projet APP
 
Chapitre 4 no sql
Chapitre 4 no sqlChapitre 4 no sql
Chapitre 4 no sql
 
Chapitre 3 spark
Chapitre 3 sparkChapitre 3 spark
Chapitre 3 spark
 
Chapitre 2 hadoop
Chapitre 2 hadoopChapitre 2 hadoop
Chapitre 2 hadoop
 
Chapitre1 introduction
Chapitre1 introductionChapitre1 introduction
Chapitre1 introduction
 

Recently uploaded

Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)dollysharma2066
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxPoojaBan
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .Satyam Kumar
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSCAESB
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfAsst.prof M.Gokilavani
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile servicerehmti665
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxKartikeyaDwivedi3
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfAsst.prof M.Gokilavani
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learningmisbanausheenparvam
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024hassan khalil
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AIabhishek36461
 

Recently uploaded (20)

★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
★ CALL US 9953330565 ( HOT Young Call Girls In Badarpur delhi NCR
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
🔝9953056974🔝!!-YOUNG call girls in Rajendra Nagar Escort rvice Shot 2000 nigh...
 
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
Call Us ≽ 8377877756 ≼ Call Girls In Shastri Nagar (Delhi)
 
Heart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptxHeart Disease Prediction using machine learning.pptx
Heart Disease Prediction using machine learning.pptx
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Churning of Butter, Factors affecting .
Churning of Butter, Factors affecting  .Churning of Butter, Factors affecting  .
Churning of Butter, Factors affecting .
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
GDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentationGDSC ASEB Gen AI study jams presentation
GDSC ASEB Gen AI study jams presentation
 
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdfCCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
CCS355 Neural Network & Deep Learning UNIT III notes and Question bank .pdf
 
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Call Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile serviceCall Girls Delhi {Jodhpur} 9711199012 high profile service
Call Girls Delhi {Jodhpur} 9711199012 high profile service
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Concrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptxConcrete Mix Design - IS 10262-2019 - .pptx
Concrete Mix Design - IS 10262-2019 - .pptx
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdfCCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
CCS355 Neural Network & Deep Learning Unit II Notes with Question bank .pdf
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
chaitra-1.pptx fake news detection using machine learning
chaitra-1.pptx  fake news detection using machine learningchaitra-1.pptx  fake news detection using machine learning
chaitra-1.pptx fake news detection using machine learning
 
Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024Architect Hassan Khalil Portfolio for 2024
Architect Hassan Khalil Portfolio for 2024
 
Past, Present and Future of Generative AI
Past, Present and Future of Generative AIPast, Present and Future of Generative AI
Past, Present and Future of Generative AI
 

POO Java Chapitre 3 Collections

  • 2. Introduction • Collection : objet qui regroupe de multiples éléments dans une seule entité. • Utilisation de collections pour - stocker, retrouver et manipuler des données - transmettre des données d ’une méthode à une autre • Par exemple, un tableau est une collection 2 • Par exemple, un tableau est une collection • Le JDK fournit d’autres types de collections sous la forme de classes et d’interfaces • Ces classes et interfaces sont dans le paquetage java.util •Avant le JDK 5.0, les collections peuvent contenir des objets de n’importe quel type • A partir du JDK 5.0, on peut indiquer le type des objets contenus dans une collection grâce à la généricitéMouna Torjmen Khemakhem
  • 3. Types de collections 2 hiérarchies principales : - Collection<E> - Map<K,V> • Map correspond aux collections indexées par des clés: un élément de type V d’une map est retrouvé rapidement si on connaît sa clé de type Krapidement si on connaît sa clé de type K 3 Mouna Torjmen Khemakhem • Une classe exemple de Collection: ArrayList import java.util.ArrayList; • Une classe exemple de Map: HashMap import java.util.HashMap;
  • 4. ArrayList import java.util.ArrayList; import java.util.Arrays; public class ArrayListTest { public static void main(String args[]) ArrayList<String> list = new ArrayList<String>(); //add list.add("Apple"); list.add("Google"); list.add("Samsung"); list.add("Microsoft"); //checking if ArrayList is empty System.out.println(« Empty ? " + list.isEmpty()); // removing an Object from ArrayList System.out.println(« Before removing : " + list); list.remove(3); //removing fourth object System.out.println("after removing : " + list); // finding index of Object in List System.out.println("What is index of Apple: "list.add("Microsoft"); //contains: use of equals method System.out.println("Does list contains Apple :" + list.contains("Apple")); System.out.println("Does list contains Verizon :" + list.contains("Verizon")); // size System.out.println("Size of ArrayList is : " + list.size()); // replacing an object System.out.println("before updating : " + list); list.set(3, "Bank of America"); System.out.println("after update : " + list); } System.out.println("What is index of Apple: " + list.indexOf("Apple")); // converting List to Array String[] array = list.toArray(new String[]{}); System.out.println("Array from ArrayList : " + Arrays.toString(array)); // removing all elements list.clear(); System.out.println("Size of ArrayList after clear : " + list.size()); } 4 Mouna Torjmen Khemakhem
  • 5. Output ArrayList /* Does list contains Apple :true Does list contains Verizon :false Size of ArrayList is : 4 list before updating : [Apple, Google, Samsung, Microsoft] list after update : [Apple, Google, Samsung, Bank of America]list after update : [Apple, Google, Samsung, Bank of America] Does this ArrayList is empty : false ArrayList before removing element : [Apple, Google, Samsung, Bank of America] ArrayList after removing element : [Apple, Google, Samsung] What is index of Apple in this list : 0 Array from ArrayList : [Apple, Google, Samsung] Size of ArrayList after clear : 0 */ http://java67.blogspot.com/2012/11/java-arraylist-example-contains-add-set.htmlMouna Torjmen Khemakhem
  • 6. HashMap import java.util.HashMap; import java.util.Iterator; public class HashMapExample{ public static void main(String args[]){ HashMap hashMap = new HashMap(); // adding value into HashMap hashMap.put("One", new Integer(1)); hashMap.put("Two", new Integer(2)); hashMap.put("Three", new Integer(3)); System.out.println("HashMap size" + hashMap.size() ); Integer one = (Integer) hashMap.get("One"); System.out.println("Value mapped with key "One" is " + one); System.out.println("Retrieving all keys "); Iterator iterator = hashMap.keySet().iterator(); while(iterator. hasNext()){ System.out.println(iterator.next()); } if(hashMap.containsValue(new Integer(1))){ System.out.println("HashMap contains 1 as value"); }else{ System.out.println("HashMap does not contain 1 as value"); } if( hashMap.containsKey("One") ){ System.out.println("HashMap contains One as key"); }else{ System.out.println("HashMap does not contain One as value"); } } System.out.println("Retrieving all values "); iterator = hashMap.entrySet().iterator(); while(iterator. hasNext()){ System.out.println(iterator.next()); } System.out.println( hashMap.remove("One") + " is removed from the HashMap."); } } 6 Mouna Torjmen Khemakhem
  • 7. Output HashMap /* OUTPUT of the above given Java HashMap Example would be : HashMap contains 3 key value pair. HashMap contains 1 as value HashMap contains One as key Value mapped with key "One" is 1 Retrieving all keys from the HashMapRetrieving all keys from the HashMap Three Two One Retrieving all values from the HashMap Three=3 Two=2 One=1 1 is removed from the HashMap. */ http://www.javadeveloper.co.in/java-example/java-hashmap-example.htmlMouna Torjmen Khemakhem