Java Collection Interface Methods - Cheat Sheet
What is Set Interface?
The Set interface in Java is a part of the [Link] package and extends the Collection interface. It represents
a collection that does not allow duplicate elements. Common implementations include HashSet,
LinkedHashSet, and TreeSet.
- HashSet: Unordered and allows null.
- LinkedHashSet: Maintains insertion order.
- TreeSet: Sorted set, no null allowed (uses natural ordering or custom Comparator).
add(E e)
Adds the specified element to the set if it is not already present.
Example:
Set<String> set = new HashSet<>();
[Link]("Java");
addAll(Collection<? extends E> c)
Adds all elements from the specified collection.
Example:
[Link]([Link]("Python", "C++"));
remove(Object o)
Removes the specified element if present.
Example:
[Link]("C++");
clear()
Removes all elements.
Example:
Java Collection Interface Methods - Cheat Sheet
[Link]();
contains(Object o)
Returns true if the set contains the specified element.
Example:
[Link]("Java");
isEmpty()
Checks if the set is empty.
Example:
[Link]();
size()
Returns the number of elements.
Example:
[Link]();
iterator()
Returns an iterator to traverse elements.
Example:
Iterator<String> it = [Link]();
toArray()
Converts the set to an array.
Example:
Object[] arr = [Link]();
retainAll(Collection<?> c)
Java Collection Interface Methods - Cheat Sheet
Keeps only the elements that are also in the specified collection.
Example:
[Link](anotherSet);
removeAll(Collection<?> c)
Removes all matching elements from the set.
Example:
[Link](anotherSet);
containsAll(Collection<?> c)
Checks if the set contains all elements of the specified collection.
Example:
[Link](anotherSet);