Clear and Clone
Part of the Logic & Flow section of Coddy's Java journey — lesson 27 of 59.
The clear() method removes all elements from a HashSet, leaving it empty.
The clone() method returns a shallow copy of the HashSet. (The elements themselves are not cloned.)
For example, first create a HashSet:
HashSet<String> set = new HashSet<>();
set.add("Coddy");To clone the set:
HashSet<String> clonedSet = (HashSet<String>) set.clone();
System.out.println(clonedSet);
// Output: [Coddy]To clear the set:
set.clear();
System.out.println(set.isEmpty());
// Output: trueWhy do we need casting with clone()?
You've already learned about casting with primitive types (like int x = (int) 3.14). The same concept applies to objects, but for a different reason.
The clone() method returns a generic Object type, not a specific HashSet<String>. This is because clone() is defined in the Object class and doesn't know what type you're cloning.
// What clone() returns:
Object cloneResult = set.clone(); // Returns Object, not HashSet<String>
// What we need:
HashSet<String> clonedSet = (HashSet<String>) set.clone(); // Cast Object → HashSet<String>The cast tells Java: "I know this Object is actually a HashSet<String>, so treat it as one."
Without the cast, you'll get a compilation error because Java won't automatically convert Object to HashSet<String>.
Challenge
EasyCreate a method named <strong>processSet</strong> that takes a HashSet of Strings as input. The method should:
- Clone the set.
- Clear the original set.
- Print the cloned set and its size in the format:
Cloned Set: [elements]Cloned Set Size: X - Print the original set (after clear) and its size in the format:
Original Set after clear: [elements]Original Set Size: Y
Cheat sheet
The clear() method removes all elements from a HashSet:
set.clear();The clone() method returns a shallow copy of the HashSet:
HashSet<String> clonedSet = (HashSet<String>) set.clone();Why casting is needed: The clone() method returns a generic Object type, so you must cast it to HashSet<String> to use it as the specific type.
Example usage:
HashSet<String> set = new HashSet<>();
set.add("Coddy");
// Clone the set (cast Object → HashSet<String>)
HashSet<String> clonedSet = (HashSet<String>) set.clone();
// Clear original set
set.clear();
System.out.println(set.isEmpty()); // Output: true
System.out.println(clonedSet); // Output: [Coddy] (clone unaffected)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;
@SuppressWarnings("unchecked")
public class Main {
public static void processSet(HashSet<String> set) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String setString = scanner.nextLine();
Type setType = new TypeToken<HashSet<String>>(){}.getType();
HashSet<String> set = new Gson().fromJson(setString, setType);
processSet(set);
}
}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