Archives Wild Code School
Java

Java Reskilling Collections 01: List

Quête 27 sur 43 · 1 image archivée

Les Collections Java : utiliser les Lists

Dans les quêtes sur les Collections Java, tu vas apprendre à partir d'exemples tirés du domaine de notre application exemple Tariff-Manager.

Dans cette quête, les Collections Java servent à stocker et à récupérer les clients de notre application Tariff-Manager. Il existe différents types de collections, et dans cette quête nous allons nous intéresser aux Lists.


🤓 À la fin de cette quête, tu sauras :

✅Comprendre comment fonctionnent les collections d'objets en Java ✅Créer et utiliser des collections en Java

👀 Contenu de la quête

Au cours de ta carrière de développeuse, tu auras souvent à stocker, classer et trier des données. Tous les langages de programmation prennent en charge l'utilisation de tableaux pour cela. Fait intéressant, Java fournit aussi le framework Collection (cadre, un ensemble d'outils tout prêts), qui contient plusieurs outils de manipulation de données très utiles.

Le problème, c'est que ce framework contient de nombreuses collections déjà existantes, et il est difficile de toutes les passer en revue pour trouver la plus adaptée à ton projet.

Cette première quête va te présenter la plus célèbre des collections : List.

Objectifs

  • Apprendre à créer des collections
  • Apprendre à modifier, insérer et supprimer des éléments dans les collections
  • Savoir parcourir les éléments d'une collection

Chapitres

  • Interface : List
  • Implémentation : ArrayList
  • Utilisation et méthodes
  • Avantages et inconvénients

👉Interface : List

Il va sans dire que les tableaux sont plutôt faciles à utiliser : tu y stockes simplement des données, puis tu es libre de reparcourir le tableau.

Mais en Java, les tableaux ont un défaut fatal : ils ont une taille fixe !

  • Si tu veux créer un tableau vide et y ajouter des données plus tard, tu dois savoir dès le départ quelle sera la taille maximale du tableau.
  • Si tu veux créer un tableau qui contient déjà des données initiales, tu ne pourras pas lui ajouter de données supplémentaires par la suite.

Pour résoudre ce problème, Java fournit une Collection (collection, un conteneur regroupant plusieurs éléments) appelée List.

Avec une List (liste, une collection ordonnée d'éléments), les items (ou éléments) qu'elle contient sont toujours ordonnés. Tout comme dans un tableau, chaque élément aura une position. En revanche, les listes te permettent, et c'est leur particularité, d'insérer un élément à la fin ou même au milieu de la structure de données (ce qui décale alors les positions des autres éléments en conséquence).

Comme List est une interface (interface, un contrat qui décrit des comportements sans dire comment ils sont réalisés), elle spécifie des comportements (c'est-à-dire des méthodes qui ajoutent ou suppriment un élément), mais pas leur implémentation.

Pour instancier une liste, tu auras besoin d'une classe qui implémente List. Fort heureusement, Java t'en fournit une : ArrayList.

👉Implémentation : ArrayList

Pour créer une nouvelle ArrayList vide, tu devras créer une nouvelle instance de la classe ArrayList et la stocker dans une référence :

Un dépôt de démonstration est fourni dans les ressources ci-dessous (également lié depuis la dernière étape de cette quête).

java
// is ok, but unneccesarily restricted by ArrayList
ArrayList<Customer> market = new ArrayList<>();
// better use interfaces if possible (List), use ArrayList as implementation
List<Customer> market = new ArrayList<>();

Ici, le mot-clé new crée une nouvelle instance qui est stockée dans la référence lunch.

Note qu'il est possible de créer des listes contenant n'importe quel objet. Mais tu ne pourras pas instancier une ArrayList en utilisant un type de données primitif. Autrement dit : il est impossible d'instancier comme ceci : ArrayList<int> ou ArrayList<char>.

Cependant, il existe des classes wrapper (classe enveloppe, qui emballe un type primitif pour en faire un objet) pour chaque type primitif, ce qui résout ce problème. Tu peux instancier ArrayList<Integer> ou ArrayList<Character>.

👉Utilisation et méthodes

Insertion

Maintenant que tu as créé ta liste, il serait utile de pouvoir y ajouter des items. Cela se fait en utilisant la méthode add qui est contenue dans la classe ArrayList.

java
Customer cathy = new Customer("Chatty Cathy");
Customer debbie = new Customer("Debbie Downer");
Customer mary = new Customer("Mary Sue");
Customer simon = new Customer("Simple Simon");

List<Customer> market = new ArrayList<>();
market.add(cathy);
market.add(debbie);
market.add(mary);
market.add(simon);

Accéder aux éléments

Chaque fois qu'un item est inséré dans la liste, un index (indice, le numéro de position d'un élément) lui est attribué. Cet index te permet d'accéder à cet élément plus tard.

Revenons à l'exemple précédent et regardons de plus près les index.

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

Donc, si tu voulais accéder au deuxième élément, tu écrirais le code suivant :

java
Customer debbie = market.get(1); // returns debbie

Suppression

Dans le même esprit, tu peux supprimer un item d'une liste via son index. Une fois supprimé, les index de tous les éléments suivants seront ajustés en conséquence :

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

market.remove(1); // removes debbie

// now returns mary, because the indices will have been adjusted
Customer mary = market.get(1); 

Remplacer un élément

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

Customer andy = new Customer("Handy Andy");

// replaces simon with andy
market.set(3, andy); 

Références et instances

Dans le langage courant, on dit parfois qu'une ArrayList contient des éléments. Mais techniquement, c'est faux ! En réalité, ces listes contiennent des références vers des éléments. Autrement dit, une ArrayList contient des liens vers des objets, pas les objets eux-mêmes.

Cette distinction n'est pas faite pour le plaisir. La présence de ces liens fait que les objets se comportent d'une manière qui pourrait te sembler étrange.

java
Customer mary = new Customer("Mary Sue");

List<Customer> market = new ArrayList<>();
market.add(mary);

// Change Mary's name after it has been added to the market
mary.setName("Bloody Mary"); 

// Get the first item from the list
Customer customer = market.get(0); 

// This will display "Bloody Mary"
System.out.println(customer.getName()); 

Vider la liste

java
market.add(cathy);
market.add(debbie);
market.add(mary);
market.add(simon);

// clears the list
market.clear(); 

Parcourir une liste

Pour parcourir une liste, tu peux prendre l'index et te servir d'une boucle for classique, ou bien employer la méthode for-each (pour-chaque, qui parcourt chaque élément sans gérer l'index toi-même).

java
// for loop
for (int i = 0; i < market.size(); i++) {
    Customer customer = market.get(i);
}

// for-each loop
for (Customer customer : market) {
    // ...
}

👉Avantages et inconvénients

Un avantage de la collection ArrayList, c'est qu'elle peut contenir des doublons.

Si tu veux exclure les doublons, trier la liste ou rechercher un item précis, ces opérations seront plus lentes qu'elles ne le seraient avec une autre collection : Set (ensemble, une collection sans doublons), mais ça, c'est un sujet pour une autre quête !

☝️Résumé

Java propose une interface Collection pour stocker, récupérer, mettre à jour et supprimer des objets Java. Pour utiliser l'interface, une implémentation doit être instanciée. Il existe plusieurs implémentations de l'interface Collection :

  • List (Interface qui étend Collection) -> ArrayList (Implémentation)
  • Set (Interface qui étend Collection) -> HashSet (Implémentation)

Dans nos exemples, nous avons utilisé List, qui est elle-même une interface. Comme implémentation pour les exemples, nous avons utilisé ArrayList. Il existe en Java de nombreuses autres implémentations de List, qui diffèrent par leur complexité et leur comportement à l'exécution, et qui doivent être évaluées selon le cas d'usage précis.

Dans cette quête, tu as appris à...

  • Créer une nouvelle collection
  • Insérer des éléments dans une collection
  • Modifier des éléments au sein d'une collection (et comprendre comment cela impacte les éléments de la collection)
  • Supprimer des éléments d'une collection
  • Parcourir les éléments d'une collection

Pour refaire ces tâches, clone l'application exemple Tariff-Manager, bascule sur la branche block_2_complete et jette un œil à dev.wcs.nad.tariffmanager.customer.CustomerCollectionTest ainsi qu'au test unitaire shouldDemonstrateJavaCollectionsWithLists.

💪Challenge

C'est un challenge de type Quizz.


Références

  • Photo d'Abe B. Ryokan sur Unsplash

Java Collections: Using Lists

In the quests about Java Collections you will learn with examples from the domain of our sample application Tariff-Manager.

In this quest Java Collections are used for storing and retrieving customers of our Tariff-Manager application. There are different types of collections, in this quest we will look at Lists.


🤓 By the end of this quest, you will:

✅Understand how collections of objects work in Java ✅Create and use collections in Java

👀 Content of the quest

During the course of your career as a developer, you will often have to store, classify and sort data. Every programming language supports the use of arrays for this purpose. Interestingly, Java also provides the Collection framework, which contains several very useful data manipulation tools.

The problem is that this framework contains many existing collections, and it is difficult to wade through them all to find the most adequate for your project.

This first quest will introduce you to the most famous collection: List.

Goals

  • Learn how to create collections
  • Learn how to modify, insert and remove elements from collections
  • Knoe how to iterate over elements in a collection

Chapters

  • Interface: List
  • Implementation: ArrayList
  • Use and Methods
  • Advantages and Disadvantages

👉Interface: List

It goes without saying that arrays are pretty easy to use, you simply store data in them, and then you are free to go back through the array.

But in Java, arrays have a fatal flaw: they have a fixed size!

  • If you want to create an empty array and add data to it later, you have to know from the very beginning what the maximum size of the array will be.
  • If you want to create an array that contains some initial data, you won't be able to add any extra data to the array at a later point.

To overcome this problem, Java provides a Collection called List.

With a list, the items (or elements) on it are always ordered. Just like in an array, each element will have a position. However, lists uniquely enable you to insert an element at the end or even in the middle of the data structure (thereby shifting the positions of the other elements respectively).

Because List is an interface, it specifies behaviours (i.e. methods that add or delete an element), but not their implementation.

In order to instantiate a list, you will need to use a class that implements List. Conveniently, Java provides you with one: ArrayList.

👉Implementation: ArrayList

To create a new empty ArrayList, you will need to create a new instance of the ArrayList class and store it in a reference:

A demo repository is provided in the resources below (also linked from the last step of this quest).

java
// is ok, but unneccesarily restricted by ArrayList
ArrayList<Customer> market = new ArrayList<>();
// better use interfaces if possible (List), use ArrayList as implementation
List<Customer> market = new ArrayList<>();

Here the new keyword creates a new instance which is stored in the lunch reference.

Note that it is possible to create lists containing any object. But you won't be able to instantiate an ArrayList using a primitive data type. In other words: it is impossible to instantiate like so: ArrayList<int> or ArrayList<char>.

However, there are wrapper classes for each primitive type, which solves this problem. You can instantiate ArrayList<Integer> or ArrayList<Character>.

👉Use and Methods

Insertion

Now that you created your list, it would be useful to be able to add items to it. This is done by using the add method which is contained within the ArrayList class.

java
Customer cathy = new Customer("Chatty Cathy");
Customer debbie = new Customer("Debbie Downer");
Customer mary = new Customer("Mary Sue");
Customer simon = new Customer("Simple Simon");

List<Customer> market = new ArrayList<>();
market.add(cathy);
market.add(debbie);
market.add(mary);
market.add(simon);

Accessing elements

Each time an item is inserted into the list, it is assigned an index. This index allows you to access that element later on.

Let's go back to the previous example, and take a closer look at the indices.

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

So if you wanted to access the second element, you would write the following code:

java
Customer debbie = market.get(1); // returns debbie

Deletion

In the same vein, you can delete an item from a list via its index. Once deleted, the indices of all the subsequent elements will be adjusted accordingly:

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

market.remove(1); // removes debbie

// now returns mary, because the indices will have been adjusted
Customer mary = market.get(1); 

Replacing an element

java
market.add(cathy);  // index 0
market.add(debbie); // index 1
market.add(mary);   // index 2
market.add(simon);  // index 3

Customer andy = new Customer("Handy Andy");

// replaces simon with andy
market.set(3, andy); 

References and instances

Colloquially, we sometimes say that an ArrayList contains elements. But technically, that's not true! In fact, these lists actually contain references to elements. In other words, an ArrayList contains links to objects, not the actual objects themselves.

This distinction isn’t being made for the fun of it. The presence of these links causes the objects to behave in a way that might seem strange to you.

java
Customer mary = new Customer("Mary Sue");

List<Customer> market = new ArrayList<>();
market.add(mary);

// Change Mary's name after it has been added to the market
mary.setName("Bloody Mary"); 

// Get the first item from the list
Customer customer = market.get(0); 

// This will display "Bloody Mary"
System.out.println(customer.getName()); 

Clearing the list

java
market.add(cathy);
market.add(debbie);
market.add(mary);
market.add(simon);

// clears the list
market.clear(); 

Iterating over a list

To iterate over a list you can take the index and make use of a classic for loop or alternatively employ the for-each method.

java
// for loop
for (int i = 0; i < market.size(); i++) {
    Customer customer = market.get(i);
}

// for-each loop
for (Customer customer : market) {
    // ...
}

👉Advantages and Disadvantages

One advantage of the ArrayList collection is that it is able to contain duplicates.

If you want to exclude duplicates, sort through the list, or search for a specific item, these operations will be slower than they would be if you were using another collection; Set, but that’s a topic for another quest!

☝️Summary

Java offers an interface Collection for storing, retrieving, updating and removing Java objects. To use the interface, an implementation has to be instantiated. There are several implementations of the Collection interface:

  • List (Interface extends Collection) -> ArrayList (Implementation)
  • Set (Interface extends Collection) -> HashSet (Implementation)

In our examples we used List, which itself is an interface. As implementation for the samples we used ArrayList. There are many other implementations of List available in Java which differ in complexity and runtime behavior and should be evaluated for the specific use case.

In this quest, you learned how to...

  • Create a new collection
  • Insert elements into a collection
  • Modify elements within a collection (and how it impacts the elements in the collection)
  • Remove elements from a collection
  • Iterate over elements in a collection

To reiterate these tasks, clone the sample application Tariff-Manager, switch to the branch block_2_complete and take a look at dev.wcs.nad.tariffmanager.customer.CustomerCollectionTest and the unit test shouldDemonstrateJavaCollectionsWithLists.

💪Challenge

This is a Quizz challenge.


References

  • Photo by Abe B. Ryokan on Unsplash