Metoda Java HashMap isEmpty () sprawdza, czy hashmap jest pusty.
Składnia isEmpty()
metody to:
hashmap.isEmpty()
Tutaj hashmap jest obiektem tej HashMap
klasy.
Parametry isEmpty ()
isEmpty()
Metoda nie ma żadnych parametrów.
Wartość zwracana przez isEmpty ()
- zwraca,
true
jeśli hashmap nie zawiera żadnych mapowań klucz / wartość - zwraca,
false
jeśli hashmap zawiera mapowania klucz / wartość
Przykład: Sprawdź, czy HashMap jest pusty
import java.util.HashMap; class Main ( public static void main(String() args) ( // create an HashMap HashMap languages = new HashMap(); System.out.println("Newly Created HashMap: " + languages); // checks if the HashMap has any element boolean result = languages.isEmpty(); // true System.out.println("Is the HashMap empty? " + result); // insert some elements to the HashMap languages.put("Python", 1); languages.put("Java", 14); System.out.println("Updated HashMap: " + languages); // checks if the HashMap is empty result = languages.isEmpty(); // false System.out.println("Is the HashMap empty? " + result); ) )
Wynik
Nowo utworzona HashMap: () Czy HashMap jest pusta? true Zaktualizowano HashMap: (Java = 14, Python = 1) Czy HashMap jest pusty? fałszywy
W powyższym przykładzie utworzyliśmy hashmap o nazwie języki. Tutaj użyliśmy tej isEmpty()
metody, aby sprawdzić, czy hashmap zawiera jakieś elementy, czy nie.
Początkowo nowo utworzony hashmap nie zawiera żadnego elementu. Dlatego isEmpty()
wraca true
. Jednak po dodaniu kilku elementów ( Python , Java ) metoda zwraca false
.