Un petit mot sur les ArrayList

Transcription

Un petit mot sur les ArrayList
Un petit mot sur les ArrayList
En java, il est possible de stocker des données autrement qu'avec des tableaux !
Comment ? Grâce à des objets collections !
L’avantage de ces objets c’est qu’ils sont dynamiques, et donc ils n'ont pas de taille à
prédéfinir ( on ne peut donc pas dépasser leur capacité).
L’ArrayList fait partie de ces objets. Il n’a pas de taille limite, et en plus, ils acceptent
n'importe quel type de données (y compris les NULL).
Pour pouvoir utiliser cet objet, il faut tout d’abord veiller à importer la classe
ArrayList qui se trouve dans le package java.util.
Vous devez savoir aussi qu'il existe tout un panel de méthodes liées à cet objet :
add( ) : permet d'ajouter un élément.
add(index, element) : ajoute l’élément à la position donnée par l’index.
get(int index) : retourne l'élément à l'index demandé.
remove(int index) : efface l'entrée à l'indice demandé.
isEmpty( ) : renvoie "vrai" si l'objet est vide.
removeAll( ): efface tout le contenu de l'objet.
contains(object element): retourne "vrai" si l'élément passé en paramètre est
dans l'objet.
iterator( ) : permet de lister tous les éléments d’un ArrayList.
indexOf (object element) : permet de connaître l’indice d’un élément de
l’ArrayList.
Exemple de code :
import java.io.*;
import java.util.ArrayList;
import java.util.Iterator;
public class Main {
public static void main(String[] args) throws IOException {
int a=1;
double d=3.1416;
ArrayList al = new ArrayList();
System.out.println("taille de l'ArrayList : " + al.size());
System.out.println("on va maintenant ajouter des éléments dans celui-ci");
al.add(12);
al.add(a);
al.add("Pourquoi pas une phrase");
al.add(d);
al.add('d');
al.add(1, "douze");
System.out.println("--------------------------------");
System.out.println("taille de l'ArrayList après ajout : " + al.size());
System.out.println("il contient actuellement : " + al);
for(int i = 0; i < al.size(); i++){
System.out.println("donnée à l'indice " + i + " = " + al.get(i));
}
System.out.println("--------------------------------");
al.remove("Oups");
al.remove(2);
al.remove("d");
System.out.println("taille après avoir retirer : " +al.size());
System.out.println("Il contient maintenant : " + al);
Iterator it = al.iterator();
while(it.hasNext()) {
Object element = it.next();
System.out.println("donnée à l'indice " + al.indexOf(element) + " = " + element);
}
}
}
Affichage :
taille de l'ArrayList : 0
on va maintenant ajouter des éléments dans celui-ci
-------------------------------taille de l'ArrayList après ajout : 6
il contient actuellement : [12, douze, 1, Pourquoi pas une phrase, 3.1416, d]
donnée à l'indice 0 = 12
donnée à l'indice 1 = douze
donnée à l'indice 2 = 1
donnée à l'indice 3 = Pourquoi pas une phrase
donnée à l'indice 4 = 3.1416
donnée à l'indice 5 = d
-------------------------------taille après avoir retirer : 5
Il contient maintenant : [12, douze, Pourquoi pas une phrase, 3.1416, d]
donnée à l'indice 0 = 12
donnée à l'indice 1 = douze
donnée à l'indice 2 = Pourquoi pas une phrase
donnée à l'indice 3 = 3.1416
donnée à l'indice 4 = d
Remarque :
Au depart l’ArrayList a bien une taille égale à 0.
Ensuite, on remarque que plus on lui ajoute des éléments, plus sa taille augmente.
Pour finir, vous voyez que lorsqu’on supprime des éléments de l’ArrayList, sa taille
diminue.
Attention, aux indices des éléments : un élément peut voir son indice être modifié
par l’ajout ou la suppression d’un élément de l’ArrayList !!!
Before you can access a collection through an iterator, you must obtain one. Each of the
collection classes provides an iterator( ) method that returns an iterator to the start of the
collection. By using this iterator object, you can access each element in the collection, one
element at a time. In general, to use an iterator to cycle through the contents of a collection,
follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection's iterator( )
2. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as
hasNext( ) returns true.
3. Within the loop, obtain each element by calling next( ).
For collections that implement List, you can also obtain an iterator by calling ListIterator. As
explained, a list iterator gives you the ability to access the collection in either the forward or
backward direction and lets you modify an element. Otherwise, ListIterator is used just like
Iterator.
Here is an example that implements these steps, demonstrating both Iterator and
ListIterator. It uses an ArrayList object, but the general principles apply to any type of
collection. Of course, ListIterator is available only to those collections that implement the
List interface.
import java.util.*;
class IteratorDemo {
public static void main(String args[]) {
ArrayList al = new ArrayList();
// add elements to the array list
al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
// use iterator to display contents of al
System.out.print("Original contents of al: ");
Iterator itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// modify objects being iterated
ListIterator litr = al.listIterator();
while(litr.hasNext()) {
Object element = litr.next();
litr.set(element + "+");
}
System.out.print("Modified contents of al: ");
itr = al.iterator();
while(itr.hasNext()) {
Object element = itr.next();
System.out.print(element + " ");
}
System.out.println();
// now, display the list backwards
System.out.print("Modified list backwards: ");
while(litr.hasPrevious()) {
Object element = litr.previous();
System.out.print(element + " ");
}
System.out.println();
}
}
The output is shown here:
Original contents of al: C A E B D F
Modified contents of al: C+ A+ E+ B+ D+ F+
Modified list backwards: F+ D+ B+ E+ A+ C+
Pay special attention to how the list is displayed in reverse. After the list is modified, litr
points to the end of the list. (Remember, litr.hasNext( ) returns false when the end of the list
has been reached.) To traverse the list in reverse, the program continues to use litr, but this
time it checks to see whether it

Documents pareils

La classe ArrayList permet de mettre en oeuvre un tableau dont la

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...

Plus en détail

ArrayList en Java

ArrayList en Java – ligne1 : déclare un ArrayList (collection) de chaînes de caractères – lignes 2-3 : y ajoute 2 objets chaînes de caractères ; remarquer la deuxième forme d’ajout : on instancie un objet qu’on ajou...

Plus en détail

•Collection Collection (conteneur) est un objet qui regroupe

•Collection Collection (conteneur) est un objet qui regroupe La notion d’itérateur est implanté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...

Plus en détail

Complements Java 5

Complements Java 5 Returns an array containing all of the elements in this collection. toArray(T[] a) Returns an array containing all of the elements in this collection; the runtime type of the returned array is that...

Plus en détail