Menu
Coddy logo textTech

Vuoto e dimensione

Fa parte della sezione Logica e flusso del percorso Java di Coddy. Lezione 26 di 59.

Il metodo isEmpty() verifica se un HashSet non contiene elementi e restituisce true se è vuoto, oppure false altrimenti.

Il metodo size() restituisce il numero di elementi nell'HashSet.

Per esempio, creiamo prima un HashSet:

HashSet<String> set = new HashSet<>();

Per verificare se il set è vuoto:

System.out.println(set.isEmpty());
// Risultato: true
set.add("Coddy");
System.out.println(set.isEmpty());
// Output: false

Il metodo size() restituisce il numero di elementi nell'insieme:

System.out.println(set.size());
// Output: 1
challenge icon

Sfida

Facile

Crea un metodo chiamato <strong>checkSet</strong> che accetta in input un HashSet di stringhe. Il metodo deve stampare due righe:

  • "Empty: <true/false>" per indicare se l'insieme è vuoto.
  • "Size: <number>" per indicare il numero di elementi nell'insieme.

Provalo tu

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void checkSet(HashSet<String> set) {
        // Scrivi qui il tuo codice
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leggi una stringa JSON che rappresenta un HashSet (ad esempio, ["Apple","Banana"])
        String setString = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> set = new Gson().fromJson(setString, setType);
        
        checkSet(set);
    }
}
quiz iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Java online