Menu
Coddy logo textTech

Aggiungere un elemento

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

Il metodo add(element) aggiunge un elemento a HashSet se non è già presente.

Crea un HashSet vuoto

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

Aggiungi "Apple" all'insieme

fruits.add("Apple");

Dopo aver eseguito il codice precedente, l'insieme fruits contiene:

["Apple"]
challenge icon

Sfida

Facile

Crea un metodo chiamato <strong>addElement</strong> che accetta due argomenti:

  1. Un HashSet di String (set)
  2. Una String (element) da aggiungere
    Il metodo deve aggiungere l'elemento fornito al set e poi stampare il set aggiornato.

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 addElement(HashSet<String> set, String element) {
        // Scrivi il tuo codice qui
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leggi la stringa JSON che rappresenta un HashSet (ad es., ["Apple","Banana"])
        String setString = scanner.nextLine();
        // Leggi l'elemento da aggiungere (ad es., "Cherry")
        String element = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> set = new Gson().fromJson(setString, setType);
        
        addElement(set, element);
    }
}
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