English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
La méthode clear() de HashMap Java supprime toutes les clés du mappage de hachage/Paires de valeurs.
La syntaxe de la méthode clear() est :
hashmap.clear();
Cette méthode clear() ne prend aucun paramètre.
La méthode clear() ne renvoie aucune valeur. Au lieu de cela, elle modifie le mappage de hachage.
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("Un", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: ", + numbers); //Supprimer toutes les mappings du HashMap numbers.clear(); System.out.println("HashMap après clear() : ") + numbers); } }
Output result
HashMap: {One=1, Two=2, Three=3} HashMap après clear() : {}
Dans l'exemple ci-dessus, nous avons créé une HashMap nommée numbers. Ici, nous utilisons la méthode clear() pour supprimer tous lesClé/Valeur.
Note:Nous pouvons utiliserHashMap remove()La méthode supprime un élément individuel du mappage de hachage.
En Java, nous pouvons utiliser la réinitialisation de HashMap pour réaliser la fonction de la méthode clear(). Par exemple
import java.util.HashMap; class Main { public static void main(String[] args) { HashMap<String, Integer> numbers = new HashMap<>(); numbers.put("Un", 1); numbers.put("Two", 2); numbers.put("Three", 3); System.out.println("HashMap: ", + numbers); //Reinitialize hashmap numbers = new HashMap<>(); System.out.println("new HashMap: ", + numbers); } }
Output result
HashMap: {One=1, Two=2, Three=3} new HashMap: {}
In the above example, we created a hashmap named numbers. The hashmap contains3elements. Note this line,
numbers = new HashMap<>();
In this case, the process does not delete all items from the hashmap. Instead, it creates a new hashmap and assigns the newly created hashmap to the number. And the old hashmap is deleted by the garbage collector.
NoteThe way the reinitialization and clear() method of HashMap works may be similar. However, they are two different processes.