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
javaSet<DataType> setName = new HashSet<>(); // or LinkedHashSet, TreeSet
5. Example Program
javaimport 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
Setnever allows duplicate elements — adding a duplicate is simply ignored, without an error.Setis an interface; common implementations includeHashSet,LinkedHashSet, andTreeSet.- The order of elements depends on which implementation you use.