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
EasyCreate a method named <strong>addElement</strong> that takes two arguments:
- A HashSet of Strings (
set) - 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);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap