Languages
[Edit]
EN

Java - add items to HashSet

0 points
Created by:
Dirask Community
6300

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. 

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