+91 81900 98289

Java HashSet

A HashSet stores each value once. add returns false when the value is already present. There is no index. Use a set when you care about membership, such as skills a learner already has.

contains is the test you want. Loop with for-each when you need to print the values. The order is not guaranteed.

Example

The second add of Java does not create a second item. size stays 1, and contains is true.

import java.util.HashSet; public class Skills { public static void main(String[] args) { HashSet<String> skills = new HashSet<>(); skills.add("Java"); skills.add("Java"); System.out.println(skills.size()); System.out.println(skills.contains("Java")); } }
String, Integer, and other well-built types work as set items because equals and hashCode agree. If you put your own class in a HashSet, those two methods must agree too.