•Collections
Transcription
•Collections
•Collections 1 ArrayList •la taille est dynamique •défini dans java.util •ArrayList<BaseType> aList = new ArrayList<BaseType>(); ArrayList<String> list = new ArrayList<String>(20); capacité initiale est 20, la taille est multipliée par 2 s’il n’y pas de place pendant l’exécution 2 •ArrayList est moins efficace qu’un vecteur ([]) •Le type de base doit être une variable de type classe (Integer, Double,...) •La version plus récente de la classe Vector Méthodes •add(valeur): ajouter au premier indice disponible •add(indice,valeur):ajouter valeur à l’indice; les autres sont repoussés de 1 •size() •set(index, valeur), get(indice) •remove(indice), clear() •boolean remove(Object element) supprimer celui du plus petit indice et les autres sont décalés et retourne true s’il y a eu suppression •boolean contains(Object element) •int indexOf(Object element), int lastIndexOf(Object element) retourne -1 si element ne fait pas partie, sinon retourne son indice • boolean isEmpty(), boolean equals(Object other) •Object[] toArray() retourne un vecteur d’Object avec les éléments de la liste 3 import java.util.ArrayList; import java.util.Scanner; public class ArrayListDemo { public static void main(String[] args) { ArrayList<String> liste = new ArrayList<String>(20); System.out.println("Entrer les elements"); boolean done = false; String next = null; String reponse; Scanner clavier= new Scanner(System.in); while (! done) { System.out.println("Entrer 1 element "); next = clavier.nextLine( ); liste.add(next); System.out.print("Entrer encore elements ?"); reponse = clavier.nextLine( ); if (!(reponse.equalsIgnoreCase( "oui"))) done = true; } System.out.println( "Liste:"); for (String element : liste) System.out.println(element); } } 4 Si on ne précise pas le type des éléments pour ArrayList, Vector les éléments sont de classe Object import java.util.*; class Point {private int x,y; public Point(int a, int b) {x=a; y=b;} public int getx() {return x;} public int gety() {return y;} public String toString() {return("x = "+x+" y = "+y);} } class Pointcol extends Point{ private String col; public Pointcol( int a,int b, String c) {super(a,b); col=c;} public String toString() {return(super.toString()+"coleur :"+col);} } 5 class Gestion_tab { private Vector clt; //private ArrayList clt; public Gestion_tab( ) {clt= new Vector(); } public void ajoute_pt(int a, int b) {Point pp= new Point(a,b); clt.add(pp);} public void p_ajoute(int a, int b, String c) {Pointcol pp= new Pointcol(a,b,c); clt.add(pp);} public void affiche_tous_pts() {for (int i=0; i <clt.size(); i++) {Object obj=clt.get(i); Point pp=(Point)obj; System.out.println(pp);// System.out.println(pp.toString());} } public int calcul_pts_col() {int nb=0; for (Object obj : clt) { if (obj instanceof Pointcol) nb++;} return nb;} public int calcul_pts_positifs() { int nb=0; for (Object obj : clt) {Point p= (Point)obj; if ( (p.getx() >=0) &&(p.gety() >=0)) nb++;} return nb;} } 6 public class TestVector { public static void main (String[] args) {Gestion_tab t=new Gestion_tab(); t.ajoute_pt(0,0);t.ajoute_pt(1,-2); t.p_ajoute(2,-5,"jaune");t.p_ajoute(1,-5,"rouge"); t.affiche_tous_pts(); System.out.println("Nombre de points positifs= " +t.calcul_pts_positifs() ); System.out.println("Nombre de points coleurs= " +t.calcul_pts_col() );} } 7 class Gestion_tab { private Vector<Point> clt; private int nb_pts_positifs; public Gestion_tab( ) {clt= new Vector<Point>(); nb_pts_positifs=0; } public void ajoute_pts(int a, int b) { {Point pp= new Point(a,b); clt.add(pp);} } public void affiche_tous_pts() {for (Point pp :clt) pp.affiche(); } public void calcul_pts_positifs() {int nb=0; for (Point pp:clt) if ((pp.getx() >0) &&(pp.gety()>0)) nb++; nb_pts_positifs=nb; System.out.println("Nombre de points positifs= "+ nb_pts_positifs);} } public class TestVector1 { public static void main (String[] args) {Gestion_tab t=new Gestion_tab(); t.ajoute_pts(1,2); t.ajoute(3,5); t.affiche_tous_pts(); t.calcul_pts_positifs();} } %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Si class Point implements Comparable<Point> public void tri() {Collections.sort(clt);} // pour trier clt 8 Collection est un objet qui regroupe plusieurs éléments en une seule unité une collection peut être utilisée pour stocker et manipuler des données et pour transmettre des données d’une méthode à une autre réduit l’effort de programmation améliore la qualité et les performances du programme permet l’interopérabilité d’API dans le package java.util 9 Collection : groupe d’objets (conteneur) •Interfaces •Implementations •Algorithmes Interfaces •Collection •Set •SortedSet •List •Queue •Map •SortedMap 10 11 Copyright © 2008 Pearson Addison-Wesley. All rights reserved 16-11 INTERFACE COLLECTION public interface Collection<E> extends Iterable<E> { // Basic Operations int size(); boolean isEmpty(); boolean contains(Object element); boolean add(E element); // Optional boolean remove(Object element); // Optional Iterator<E> iterator(); // Bulk Operations boolean containsAll(Collection<?> c); boolean addAll(Collection<? extends E> c); // Optional boolean removeAll(Collection<?> c); // Optional boolean retainAll(Collection<?> c); // Optional void clear(); // Optional // Array Operations Object[] toArray(); } méthode optionnelle public boolean add (E element) {throw new UnsupportedOperationException();} Il s’agit d’une exception dérivée de RunTimeException il n’y a pas throw et catch 12 Iterator Un itérateur permet de parcourir une collection La notion d’itérateur est réalisée en Java par l’interface Iterator public boolean hasNext() public Object next() public void remove() (enlève le dernier élément retourné) for (Iterator i = collec.iterator(); i.hasNext(); ) { Object o = i.next(); // Récupère l’élément et passe au suivant // ... } 13 SET est une collection sans duplication d’élément (les mêmes méthodes mais en tenant compte duplications) Implémentations: HashSet (sans ordre) TreeSet ( avec un ordre) import java.util.*; public class FindDups { public static void main(String args[]) { Set<String> s = new HashSet<String>(); for (String a : args) if (!s.add(a)) System.out.println("mots dupliques: "+a); System.out.println(s.size()+ " mots distincts: "+s); } } 14 import java.util.*; public class FindDups2 { public static void main(String args[]) { Set<String> uniques = new HashSet<String>(); Set<String> dups = new HashSet<String>(); for (String a : args) if (!uniques.add(a)) dups.add(a); uniques.removeAll(dups); // difference des ensembles System.out.println(" mots uniques: " + uniques); System.out.println(" mots dupliques: " + dups); } } si la liste d’arguments: a bb a b c b d mots uniques: [d, c, bb] mots dupliques: [b, a]: 15 LIST :un ensemble ordonné, duplication possible public interface List<E> extends Collection<E> { // Positional Access E get(int index); E set(int index, E element); // Optional boolean add(E element); // Optional void add(int index, E element); // Optional E remove(int index); // Optional abstract boolean addAll(int index, Collection<? extends E> c); //Optional // Search int indexOf(Object o); int lastIndexOf(Object o); // Iteration ListIterator<E> listIterator(); ListIterator<E> listIterator(int index); // Range-view List<E> subList(int from, int to); } 16 Implémentations ArrayList, Vector, LinkedList public interface ListIterator<E> extends Iterator<E> { boolean hasNext(); E next(); boolean hasPrevious(); E previous(); int nextIndex(); int previousIndex(); void remove(); // Optional void set(E o); // Optional void add(E o); // Optional } public int indexOf(E o) { for (ListIterator<E> i = listIterator(); i.hasNext(); ) if (o==null ? i.next()==null : o.equals(i.next())) return i.previousIndex(); return -1; // Object not found } public static <E> void replace(List<E> s, E val, E newVal) { for (ListIterator<E> i = s.listIterator(); i.hasNext(); ) if (val==null ? i.next()==null : val.equals(i.next())) 17 i.set(newVal); } Algorithms sort: Sorts a List using a merge sort algorithm, which provides a fast, stable sort. (A stable sort is one that does not reorder equal elements.) shuffle: Randomly permutes the elements in a List. reverse: Reverses the order of the elements in a List. rotate: Rotates all of the elements in a List by a specified distance. swap: Swaps the elements at specified positions in in a List. replaceAll: Replaces all occurrences of one specified value with another. fill: Overwrites every element in a List with the specified value. copy: Copies the source List into the destination List. binarySearch: Searches for an element in an ordered List using the binary search algorithm. indexOfSubList: Returns the index of the first sublist of one List that is equal to another. lastIndexOfSubList: Returns the index of the last sublist of one List that is equal to another. 18 MAP (tableau associatif) est une collection qui permet de stocker des associations (clé, valeur) •Une clé peut correspondre au plus à une valeur • Deux tableaux associatifs sont égaux s’ils représentent les mêmes associations clé/valeur Implémentations HashMap<K,V> HashTable 19 // Basic Operations boolean is Empty() V put(Object key, Object value); //Optional V get(Object key) boolean containsKey(Object key); boolean containsValue(Object value); int size(); // Bulk Operations void putAll(Map<?extends K, ,?extends V> t); V remove(Object key); //Optional //View operations Collection<V> values() 20 import java.util.*; public class Freq { public static void main(String args[]) { Map<String, Integer> m = new HashMap<String, Integer>(); //Entrer la liste par la ligne de commande for (String a : args) { int freq = m.get(a); m.put(a, freq==0 ? 1 : freq + 1); } } System.out.println(m.size() + " mots distincts:"); System.out.println(m); } f 21
Documents pareils
•Collection Collection (conteneur) est un objet qui regroupe
Collection (conteneur) est un objet qui regroupe
plusieurs éléments en une seule unité
une collection peut être utilisée pour stocker et manipuler
des données et pour transmettre des données
d’une ...
transparents
Pile (Stack) avec une LinkedList
import java.util.*;
public class Pile {
private LinkedList l = new LinkedList();
public void ajouter(Object o){
l.addFirst(o);
La classe ArrayList permet de mettre en oeuvre un tableau dont la
Exemple [voir]
import java.util.ArrayList;
import java.util.Iterator;
public class programme {
public static void main(String[] args) {
ArrayList tableau = new ArrayList(500);
for(int i = 1; i <= 1...