A HashSet in Java is a collection that uses a hash table for storing elements. It does not allow duplicate elements and provides constant time performance for basic operations like add, remove, and contains, assuming the hash function disperses the elements properly.
import java.util.HashSet;
class HashSetExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Apple");
set.add("Banana");
set.add("Orange");
System.out.println(set);
}
}
HashSet is part of the Java Collections Framework and implements the Set interface. It does not guarantee the order of elements and allows null values.
Console Output:
[Apple, Banana, Orange]
The add() method is used to add elements to the HashSet. If the element is already present, the set will not change, and the method will return false.
import java.util.HashSet;
class HashSetAddExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Mango");
set.add("Mango"); // Duplicate
set.add("Grapes");
System.out.println(set);
}
}
HashSet automatically handles duplicates by ignoring them. Therefore, even if you try to add a duplicate element, it won’t be added.
Console Output:
[Mango, Grapes]
You can remove elements from a HashSet using the remove() method. This method returns true if the element was present and removed, otherwise false.
import java.util.HashSet;
class HashSetRemoveExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Cherry");
set.add("Peach");
set.remove("Cherry");
System.out.println(set);
}
}
Once an element is removed, it is no longer part of the HashSet, and any further operations on it will not affect the set.
Console Output:
[Peach]
The contains() method checks whether a specific element is present in the HashSet. It returns true if the element is found, otherwise false.
import java.util.HashSet;
class HashSetContainsExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Lemon");
set.add("Lime");
System.out.println(set.contains("Lemon"));
System.out.println(set.contains("Orange"));
}
}
The contains() method is useful for checking element existence without manually iterating through the HashSet.
Console Output:
true
false
You can iterate over elements in a HashSet using an Iterator or a for-each loop. This allows you to access each element sequentially.
import java.util.HashSet;
import java.util.Iterator;
class HashSetIteratorExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Kiwi");
set.add("Pineapple");
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
Using an iterator is a safe way to iterate over a HashSet, especially when you need to remove elements during iteration.
Console Output:
Kiwi
Pineapple
The size() method returns the number of elements in the HashSet. The clear() method removes all elements, leaving the set empty.
import java.util.HashSet;
class HashSetSizeClearExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add("Strawberry");
set.add("Blueberry");
System.out.println("Size: " + set.size());
set.clear();
System.out.println("Size after clear: " + set.size());
}
}
These methods are essential for managing the HashSet's lifecycle, such as resetting it or checking its capacity before operations.
Console Output:
Size: 2
Size after clear: 0
HashSet allows null elements. However, adding multiple nulls will still result in only one null value being stored.
import java.util.HashSet;
class HashSetNullExample {
public static void main(String[] args) {
HashSet set = new HashSet();
set.add(null);
set.add(null);
System.out.println(set);
}
}
While HashSet supports null values, it's crucial to handle them carefully to avoid NullPointerExceptions in operations.
Console Output:
[null]
HashSet provides constant time performance for basic operations like add, remove, and contains, provided the hash function disperses elements properly across the buckets.
import java.util.HashSet;
class HashSetPerformanceExample {
public static void main(String[] args) {
HashSet set = new HashSet();
for (int i = 0; i < 1000000; i++) {
set.add(i);
}
System.out.println("Added 1,000,000 elements.");
}
}
HashSet is suitable for large datasets where quick insertion, deletion, and lookup are required, making it ideal for caching and indexing applications.
Console Output:
Added 1,000,000 elements.
While HashSet is based on a hash table, TreeSet is based on a tree structure. HashSet offers constant time performance, whereas TreeSet guarantees log(n) time complexity for basic operations and maintains elements in sorted order.
import java.util.HashSet;
import java.util.TreeSet;
class SetComparisonExample {
public static void main(String[] args) {
HashSet hashSet = new HashSet();
TreeSet treeSet = new TreeSet();
hashSet.add("Banana");
hashSet.add("Apple");
treeSet.add("Banana");
treeSet.add("Apple");
System.out.println("HashSet: " + hashSet);
System.out.println("TreeSet: " + treeSet);
}
}
Choose HashSet for performance-critical applications where order does not matter, and TreeSet when sorted order is required.
Console Output:
HashSet: [Banana, Apple]
TreeSet: [Apple, Banana]
Newsletter
Subscribe to our newsletter for weekly updates and promotions.
Wiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWiki E-Learning
E-LearningComputer Science and EngineeringMathematicsNatural SciencesSocial SciencesBusiness and ManagementHumanitiesHealth and MedicineEngineeringWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWikiCode
Programming LanguagesWeb DevelopmentMobile App DevelopmentData Science and Machine LearningDatabase ManagementDevOps and Cloud ComputingSoftware EngineeringCybersecurityGame DevelopmentWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki News
World NewsPolitics NewsBusiness NewsTechnology NewsHealth NewsScience NewsSports NewsEntertainment NewsEducation NewsWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterWiki Tools
JPEG/PNG Size ReductionPDF Size CompressionPDF Password RemoverSign PDFPower Point to PDFPDF to Power PointJPEG to PDF ConverterPDF to JPEG ConverterWord to PDF ConverterCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesCompany
About usCareersPressCompany
About usCareersPressCompany
About usCareersPressLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesLegal
TermsPrivacyContactAds PoliciesAds Policies