📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
In this guide, you will learn about the HashSet clone() method in Java programming and how to use it with an example.
1. HashSet clone() Method Overview
Definition:
The clone() method of the HashSet class in Java returns a shallow copy of the HashSet instance: the elements themselves are not cloned.
Syntax:
public Object clone()
Parameters:
The method does not take any parameters.
Key Points:
- The clone() method creates a new HashSet instance and inserts all elements of the original set into the new set.
- Changes to the cloned HashSet instance do not affect the original HashSet instance and vice versa.
- The clone() method does not clone the elements themselves; it creates a new set containing references to the same elements.
- The method is not type-safe; it returns an object of type Object, so a type cast is needed to assign it to a HashSet variable.
- The clone() method is generally used to get a backup of the original object in memory.
2. HashSet clone() Method Example
import java.util.HashSet;
public class HashSetCloneExample {
public static void main(String[] args) {
HashSet<String> originalSet = new HashSet<>();
// Adding elements to the original HashSet
originalSet.add("Apple");
originalSet.add("Banana");
originalSet.add("Cherry");
// Printing the original HashSet
System.out.println("Original HashSet: " + originalSet);
// Cloning the original HashSet
HashSet<String> clonedSet = (HashSet<String>) originalSet.clone();
// Printing the cloned HashSet
System.out.println("Cloned HashSet: " + clonedSet);
// Adding a new element to the cloned HashSet
clonedSet.add("Date");
// Printing both HashSets after modification
System.out.println("Original HashSet after modification: " + originalSet);
System.out.println("Cloned HashSet after modification: " + clonedSet);
}
}
Output:
Original HashSet: [Banana, Cherry, Apple] Cloned HashSet: [Banana, Cherry, Apple] Original HashSet after modification: [Banana, Cherry, Apple] Cloned HashSet after modification: [Date, Banana, Cherry, Apple]
Explanation:
In this example, we have an original HashSet containing some elements.
We then clone this HashSet using the clone() method and make a modification to the cloned set by adding a new element.
The output demonstrates that the original HashSet remains unaffected by changes to the cloned set, thereby showcasing that a shallow copy of the HashSet has been created.
Comments
Post a Comment
Leave Comment