Menu
Coddy logo textTech

Adding an Element

Part of the Logic & Flow section of Coddy's Java journey — lesson 23 of 59.

The add(element) method adds an element to the HashSet if it is not already present.

Create an empty HashSet

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

Add "Apple" to the set

fruits.add("Apple");

After executing the above code, the set fruits contains:

["Apple"]
challenge icon

Challenge

Easy

Create a method named <strong>addElement</strong> that takes two arguments:

  1. A HashSet of Strings (set)
  2. A String (element) to add
    The method should add the given element to the set and then print the updated set.

Try it yourself

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) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Read JSON string representing a HashSet (e.g., ["Apple","Banana"])
        String setString = scanner.nextLine();
        // Read the element to add (e.g., "Cherry")
        String element = scanner.nextLine();
        
        Type setType = new TypeToken<HashSet<String>>(){}.getType();
        HashSet<String> set = new Gson().fromJson(setString, setType);
        
        addElement(set, element);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow