The Set interface in Java extends the Collection interface and represents an unordered collection of elements that does not allow duplicates. It is used when uniqueness of elements is required.
1. Key Implementations of Set
Class
Description
HashSet
Uses a hash table (fastest operations, no order).
LinkedHashSet
Maintains insertion order (slower than HashSet).
TreeSet
Stores elements in sorted order (uses Comparable or Comparator).
2. Set Interface Methods (Detailed)
📌 Basic Operations
Method
Description
Example
boolean add(E e)
Adds an element if not already present.
set.add("Java");
boolean remove(Object o)
Removes the specified element.
set.remove("Java");
int size()
Returns the number of elements.
int size = set.size();
boolean isEmpty()
Checks if the set is empty.
if (set.isEmpty()) {...}
void clear()
Removes all elements.
set.clear();
boolean contains(Object o)
Checks if the element exists.
if (set.contains("Java")) {...}
📌 Bulk Operations (Working with Multiple Elements)
Method
Description
Example
boolean addAll(Collection<? extends E> c)
Adds all elements from another collection.
set.addAll(otherSet);
boolean removeAll(Collection<?> c)
Removes all elements present in the given collection.
set.removeAll(toRemove);
boolean retainAll(Collection<?> c)
Keeps only elements present in the given collection.
set.retainAll(toKeep);
📌 Iteration & Conversion
Method
Description
Example
Iterator<E> iterator()
Returns an iterator for sequential access.
Iterator<String> it = set.iterator();
Object[] toArray()
Converts the set to an array.
Object[] arr = set.toArray();
<T> T[] toArray(T[] a)
Converts the set to a typed array.
String[] arr = set.toArray(new String[0]);
3. Example: Using Set Methods
importjava.util.*;publicclassSetExample{publicstaticvoidmain(String[]args){Set<String>languages=newHashSet<>();// 1. Adding elementslanguages.add("Java");languages.add("Python");languages.add("Java");// Duplicate ignoredSystem.out.println(languages);// [Java, Python] (order may vary)// 2. Checking size and emptinessSystem.out.println("Size: "+languages.size());// 2System.out.println("Is empty? "+languages.isEmpty());// false// 3. Removing elementslanguages.remove("Python");System.out.println(languages);// [Java]// 4. Checking if an element existsSystem.out.println("Contains Java? "+languages.contains("Java"));// true// 5. Iterating using IteratorIterator<String>it=languages.iterator();while(it.hasNext()){System.out.println(it.next());}// 6. Converting to arrayString[]arr=languages.toArray(newString[0]);System.out.println(Arrays.toString(arr));// [Java]}}
4. Key Points to Remember
✔ Set does not allow duplicates (unlike List).
✔ No order guarantee (except LinkedHashSet and TreeSet).
✔ No index-based operations (unlike List).
✔ Common implementations: HashSet (fastest), LinkedHashSet (ordered), TreeSet (sorted).
5. When to Use Set?
✅ When uniqueness of elements is required.
✅ When order does not matter (use LinkedHashSet for order).
✅ When sorted elements are needed (use TreeSet).
Summary Table of Key Methods
Method
Action
add(E e)
Adds an element if not present
remove(Object o)
Removes the specified element
contains(Object o)
Checks if element exists
size()
Returns number of elements
iterator()
Returns an iterator
toArray()
Converts to array
This covers all major methods of the Set interface in Java. 🚀 Let me know if you need further clarifications!
Top comments (0)
Subscribe
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Top comments (0)