Newer
Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# Java Collection Framework (JCF)
JCF contient :
* Interfaces
* Implémentations
* Algorithmes
Avantages :
* moins d'efforts
* plus d'efficacité et de qualité
* liens plus faciles entre différentes APIs
* code plus réutilisable
```mermaid
classDiagram
Collection <|-- Set
Collection <|-- List
Collection <|-- Queue
Set <|-- HashSet
HashSet <|-- LinkedHashSet
Set <|-- SortedSet
SortedSet <|-- TreeSet
List <|-- ArrayList
List <|-- Stack
List <|-- LinkedList
Queue <|-- LinkedList
Queue <|-- PriorityQueue
Map <|-- SortedMap
SortedMap <|-- TreeMap
Map <|-- HashMap
HashMap <|-- LinkedHashMap
<<interface>> Collection
<<interface>> Set
<<interface>> List
<<interface>> Queue
<<interface>> SortedSet
<<interface>> Map
<<interface>> SortedMap
```
## Interface [`Collection`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Collection.html)
```java
interface Collection<E> {
// opérations de base
int size();
boolean isEmpty();
boolean contains(Object o);
boolean add(E e); // facultative
boolean remove(Object o); // facultative
// opérations de masse
boolean containsAll(Collection<?> c);
boolean addAll(Collection<? extends E> c); // facultative
boolean removeAll(Collection<?> c); // facultative
void clear(); // facultative
// opérations tableaux
Object[] toArray();
<T> T toArray(T[] a);
// itérateur
Iterator<E> iterator();
}
```
Méthodes facultatives : `UnsupportedOperationException`.
En plus de ces méthodes, chaque implémentation doit contenir un constructeur par défaut et un constructeur par recopie
```java
public class MyCollection<E> implements Collection<E> {
public MyCollection() {
// crée une collection vide
}
public MyCollection(Collection<? extends E> c) {
// crée une collection qui contient les mêmes éléments que c
}
}
```
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
### Interface [`Iterator`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Iterator.html)
```java
interface Iterator<E> {
boolean hasNext();
E next();
void remove(); // facultative
}
```
Parcour typique d'une collection avec itérateur :
```java
Collection<Truc> trucs = ...;
Iterator<Truc> it = trucs.iterator();
while (it.hasNext()) {
Truc truc = it.next();
// traiter truc
}
```
La boucle foreach utilise un itérateur !
```java
for (Truc truc : trucs) {
// traiter truc
}
```
est juste un raccourci pour la boucle `while` précédente.
Dans certains cas particuliers les implémentations *doivent* déclencher des exceptions.
```java
Iterator<Truc> it = trucs.iterator();
while(it.hasNext()) it.next();
it.next(); // NoSuchElementException
```
`remove()` supprime *l'élément renvoyé par le dernier appel de* `next()`.
```java
Iterator<Truc> it = trucs.iterator();
it.remove(); // IllegalStateException
it = trucs.iterator();
Truc a = it.next();
Truc b = it.next();
it.remove(); // supprime b
it.remove(); // IllegalStateException
```
Extrait de la documentation de `remove()` :
> The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method, unless an overriding class has specified a concurrent modification policy.
```java
Collection<Animal> animaux = ...;
// À ne JAMAIS faire
Iterator<Animal> it = animaux.iterator();
while (it.hasNext()) {
Animal animal = it.next();
if (animal.estPoilu()) animaux.remove(animal);
}
// .. ni la forme équivalente
for (Animal animal : animaux) {
if (animal.estPoilu()) animaux.remove(animal);
}
// La bonne façon de faire :
Iterator<Animal> it = animaux.iterator();
while(it.hasNext()) {
Animal animal = it.next();
if (animal.estPoilu()) it.remove();
}
```
### Implémentation d'une collection *from skratch*
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
Une collection qui stocke ses éléments dans un tableau. Implémentation inspirée de `ArrayList`.
Problématique principale : lorsque le tableau est rempli, il faut reallouer et recopier tous les éléments et cela coûte cher. Faire moins de telles opérations mais sans utiliser trop de mémoire.
```java
public class MyCollection<E> implements Collection<E> {
private static final int INITIAL_CAPACITY = 10;
private static final int CAPACITY_INCREMENT = 10;
private E[] elements;
private int size;
// Helpers
private void fastAdd(E e) {
elements[size++] = e;
}
private void fastRemove(int i) {
System.arraycopy(elements, i + 1, elements, i, size - i - 1);
elements[--size] = null;
}
private int indexOf(Object o) {
if (o == null) {
for (int i = 0; i < size; i++) {
if (elements[i] == null) return i;
}
} else {
for (int i = 0; i < size; i++) {
if (o.equals(elements[i])) return i;
}
}
return -1;
}
private void incrementCapacity(int c) {
elements = Arrays.copyOf(elements, elements.length + c);
}
// Constructors
public MyCollection(int n) {
elements = (E[]) new Object[n];
size = 0;
}
public MyCollection() {
this(INITIAL_CAPACITY);
}
public MyCollection(Collection<? extends E> c) {
this(c.size() + CAPACITY_INCREMENT);
for (E e : c) fastAdd(e);
}
// Simple operations
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0;
}
public boolean contains(Object o) {
return indexOf(o) != -1;
}
public boolean add(E e) {
if (size == elements.length) incrementCapacity(CAPACITY_INCREMENT);
fastAdd(e);
return true;
}
public boolean remove(Object o) {
int i = indexOf(o);
if (i != -1) fastRemove(i);
return i != -1;
}
// Bulk operations
public boolean containsAll(Collection<?> collection) {
for (Object o : collection) {
if (!contains(o)) return false;
}
return true;
}
public boolean addAll(Collection<? extends E> collection) {
int missing = size + collection.size() - elements.length;
if (missing > 0) incrementCapacity(missing + CAPACITY_INCREMENT);
for (E e : collection) fastAdd(e);
return collection.size() > 0;
}
public boolean removeAll(Collection<?> collection) {
boolean res = false;
for (Object o : collection) {
while (remove(o)) res = true;
}
return res;
}
public boolean retainAll(Collection<?> collection) {
boolean res = false;
int i = 0;
while (i < size) {
if (!collection.contains(elements[i])) {
fastRemove(i);
res = true;
} else {
i++;
}
}
return res;
}
public void clear() {
Arrays.fill(elements, 0, size, null);
size = 0;
}
// Iterators
public Iterator<E> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<E> {
private int iNext = 0;
private int iPrev = -1;
public boolean hasNext() {
return iNext < size;
}
public E next() {
if (iNext >= size) throw new NoSuchElementException();
iPrev = iNext++;
return elements[iPrev];
}
public void remove() {
if (iPrev == -1) throw new IllegalStateException();
fastRemove(iPrev);
iNext--;
iPrev = -1;
}
}
// Arrays
public Object[] toArray() {
return Arrays.copyOf(elements, size);
}
public <T> T[] toArray(T[] ts) {
if (size <= ts.length) {
System.arraycopy(elements, 0, ts, 0, size);
} else {
ts = (T[]) Arrays.copyOf(elements, size, ts.getClass());
}
return ts;
}
}
```
### Implémentation à partir de [`AbstractCollection`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/AbstractCollection.html)
```java
public class MyCollection<E> extends AbstractCollection<E> { ... }
```
Seulement deux méthodes abstraites : `size()` et `iterator()`. Mais pour faire une collection opérationnelle et efficace, il faut surcharger d'autres. Pour savoir lesquelles, lire la documentation.
**Exemple 1** `isEmpty()`
> This implementation returns size() == 0.
**Exemple 2** `add()`
> This implementation always throws an UnsupportedOperationException.
**Exemple 3** `addAll()`
> This implementation iterates over the specified collection, and adds each object returned by the iterator to this collection, in turn.
## Ordre
**Exemple**
```java
List<String> l = new ArrayList<>();
l.add("Charlie"); l.add("Alice"); l.add("Bob");
Collections.sort(l); // ["Alice", "Bob", "Charlie"]
```
Comment ça marche ?
### Ordre naturel
```java
interface Comparable<T> {
int compareTo(T t);
}
```
La classe `String` implémente `Comparable<String>`.
```java
class Employe implements Comparable<Employe> {
private String nom;
private int salaire;
...
public int compareTo(Employe e) {
return nom.compareTo(e.nom);
}
}
```
```java
List<Employe> personnel = ...;
...
Collections.sort(personnel); // Trié par ordre alphabétique des noms
```
Mais comment on fait pour trier en ordre décroissant des salaires ?
### Comparateurs
```java
interface Comparator<T> {
int compare(T t1, T t2);
}
```
```java
Collections.sort(personnel, (e1, e2) -> e2.getSalaire() - e1.getSalaire());
```
Certains collections utilisent l'ordre pour rendre certaines opérations plus efficaces.
```java
SortedSet<Employe> personnel = new TreeSet<>(); // ordre naturel
SortedSet<Employe> personnel = new TreeSet<>((e1, e2) -> e2.getSalaire() - e1.getSalaire());