How to initialise HashSet while declaring in Java

Before delving into initialization, let’s understand the allure of a HashSet. This data structure, based on the principles of a set in mathematics, provides rapid access to elements and ensures uniqueness—no duplicates allowed. Perfect for scenarios where order doesn’t matter, and you need swift membership checks.

Techniques for Initializing HashSet During Declaration

Method 1: Traditional Declaration and Initialization

The most straightforward approach involves declaring and initializing the HashSet in two steps:

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

This single line sets the stage for a HashSet named myHashSet, ready to accommodate strings.

Method 2: Initializing with Elements

To go a step further, initialize the HashSet with elements during declaration:

HashSet<String> fruits = new HashSet<>(Arrays.asList("Apple", "Banana", "Orange"));

Method 3: Static Initialization Block

For dynamic initialization, use a static initialization block:

HashSet<Character> vowels;

{
    vowels = new HashSet<>();
    vowels.add('a');
    vowels.add('e');
    vowels.add('i');
    vowels.add('o');
    vowels.add('u');
}

Conclusion

Mastering HashSet initialization during declaration empowers Java developers with flexibility and efficiency. Whether initializing an empty set or populating it with elements, these methods cater to diverse use cases. As you embark on your Java journey, incorporating HashSet initialization techniques will undoubtedly elevate your coding prowess. Embrace the simplicity, unleash the power, and let your HashSet initialization in Java shine.

Related Post