Languages
[Edit]
EN

Java - add items to HashSet

0 points
Created by:
rmlocerd
302

In this article, we would like to show you how to add items to the HashSet in Java.

Quick solution:

Set<String> animals = new HashSet<>();
animals.add("Dog");

 

Practical example

In this example, we add three elements to the animals HashSet using add() method.

import java.util.*;

public class Example {

    public static void main(String[] args) {
        Set<String> animals = new HashSet<>();

        animals.add("Dog");
        animals.add("Cat");
        animals.add("Parrot");

        System.out.println(animals);  // [Parrot, Cat, Dog]
    }
}

Output:

[Parrot, Cat, Dog]

Note:

HashSet doesn't accept duplicates. It only stores unique values. 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - HashSet

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join