Skip to content
C

Set

Set is an interface in the Collection Framework that represents a group of unique elements — duplicate values are simply not allowed.


1. What is a Set?

Set is an interface in the Collection Framework that represents a group of unique elements — duplicate values are simply not allowed. Unlike List, a Set generally does not guarantee any specific order of elements (though some implementations do).

2. Why is it used?

Set is ideal when you need to store data but must ensure that no value is repeated — like storing a list of unique usernames or unique email addresses.

3. Real-Life Example

Think of a collection of unique stamps in an album, where a collector never keeps two copies of exactly the same stamp. A Set behaves the same way — automatically preventing duplicate entries.

4. Syntax

java
Set<DataType> setName = new HashSet<>(); // or LinkedHashSet, TreeSet

5. Example Program

java
import java.util.Set; import java.util.HashSet; public class SetDemo { public static void main(String[] args) { Set<String> names = new HashSet<>(); names.add("Riya"); names.add("Riya"); // duplicate, ignored System.out.println(names); } }

Output:

[Riya]

6. Key Points to Remember

  • Set never allows duplicate elements — adding a duplicate is simply ignored, without an error.
  • Set is an interface; common implementations include HashSet, LinkedHashSet, and TreeSet.
  • The order of elements depends on which implementation you use.