📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.
🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
Important Key Points about the Set Interface
Here are some key points about the Set interface in Java:
Unique Elements:
The Set is a Collection that cannot contain duplicate elements. It models the mathematical set abstraction.
Ordering:
The elements in a Set can be sorted in ascending order by using TreeSet implementation class. HashSet implementation class provides no ordering guarantees. The LinkedHashSet implementation class maintains the insertion order.
Null Elements:
All Set implementations permit, at most, one null element, if they permit null elements at all.
Methods:
The Set interface includes all the methods of the Collection interface and adds a stronger contract on the behavior of the equals and hashCode operations, allowing Set instances to be compared meaningfully even if their implementation types differ.
Subinterfaces and Implementations:
The commonly used classes that implement the Set interface are HashSet, LinkedHashSet, and TreeSet.
No Position Access:
Unlike the List interface, the Set interface doesn't provide any methods to access the element by an index as Set doesn't maintain any fixed order.
Use-cases:
The Set is useful when you want to prevent duplicate values and do not care about the order of elements.
Equality:
Two Set objects are considered equal if they contain the same elements, regardless of the order.
Thread Safety:
None of the Set implementations in the Java Collection Framework are thread-safe. But you can make them thread-safe using Collections.synchronizedSet() and CopyOnWriteArraySet.
Remember, you cannot instantiate Set directly as it is an interface. You need to instantiate a class that implements the Set interface. There are three general-purpose Set implementations: HashSet, TreeSet, and LinkedHashSet.
Set Interface Hierarchy Diagram
Set Interface APIs/Methods
Below are the important Set interface methods with descriptions:
- boolean add(E e) - This method adds the specified element to this set if it is not already present (optional operation).
- boolean addAll(Collection<? extends E> c) - This method adds all of the elements in the specified collection to this set if they're not already present (optional operation).
- _void clear() _- This method removes all of the elements from this set (optional operation).
- boolean contains(Object o) - This method returns true if this set contains the specified element.
- boolean containsAll(Collection<?> c) - This method returns true if this set contains all of the elements of the specified collection.
- boolean equals(Object o) - This method compares the specified object with this set for equality.
- int hashCode() - This method returns the hash code value for this set.
- boolean isEmpty() - This method returns true if this set contains no elements.
- Iterator iterator() - This method returns an iterator over the elements in this set.
- boolean remove(Object o) - This method removes the specified element from this set if it is present (optional operation).
- boolean removeAll(Collection<?> c) - This method removes from this set all of its elements that are contained in the specified collection (optional operation).
- boolean retainAll(Collection<?> c) - This method retains only the elements in this set that are contained in the specified collection (optional operation).
- int size() - This method returns the number of elements in this set (its cardinality).
- default Spliterator spliterator() - This method creates a Spliterator over the elements in this set.
Example 1: Set Interface with Its HashSet Implementation Class
import java.util.HashSet; import java.util.Set; public class CreateHashSetExample { public static void main(String[] args) { // Creating a HashSet Set<String> daysOfWeek = new HashSet<>(); // Adding new elements to the HashSet daysOfWeek.add("Monday"); daysOfWeek.add("Tuesday"); daysOfWeek.add("Wednesday"); daysOfWeek.add("Thursday"); daysOfWeek.add("Friday"); daysOfWeek.add("Saturday"); daysOfWeek.add("Sunday"); // Adding duplicate elements will be ignored daysOfWeek.add("Monday"); System.out.println(daysOfWeek); } }
Output:
[Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
Example 2: Set Interface with Its LinkedHashSet Implementation Class
// Creating a HashSet LinkedHashSet<String> daysOfWeek = new LinkedHashSet<>(); // Adding new elements to the HashSet daysOfWeek.add("Monday"); daysOfWeek.add("Tuesday"); daysOfWeek.add("Wednesday"); daysOfWeek.add("Thursday"); daysOfWeek.add("Friday"); daysOfWeek.add("Saturday"); daysOfWeek.add("Sunday"); // Adding duplicate elements will be ignored daysOfWeek.add("Monday"); System.out.println(daysOfWeek);
Output:
[Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday]
Read more about LinkedHashSet class with examples at Guide to LinkedHashSet Class.
Example 3: Set Interface with Its TreeSet Implementation Class
// Creating a TreeSet TreeSet<String> fruits = new TreeSet<>(); // Adding new elements to a TreeSet fruits.add("Banana"); fruits.add("Apple"); fruits.add("Pineapple"); fruits.add("Orange"); System.out.println("Fruits Set : " + fruits); // Duplicate elements are ignored fruits.add("Apple"); System.out.println("After adding duplicate element \"Apple\" : " + fruits); // This will be allowed because it's in lowercase. fruits.add("banana"); System.out.println("After adding \"banana\" : " + fruits);
Output:
Fruits Set : [Apple, Banana, Orange, Pineapple] After adding duplicate element "Apple" : [Apple, Banana, Orange, Pineapple] After adding "banana" : [Apple, Banana, Orange, Pineapple, banana]
Note that in this example, duplicate elements are ignored.
Set Interface Implementation Classes
There are three general-purpose Set implementations:Below are the special-Purpose Set interface Implementations:
Related Collections Framework Interfaces
- Collections Framework - The Collection Interface
- Collections Framework - The Set Interface
- Collections Framework - The SortedSet Interface
- Collections Framework - The List Interface
- Collections Framework - The Queue Interface
- Collections Framework - The Deque Interface
- Collections Framework - The Map Interface
- Collections Framework - The SortedMap Interface
Comments
Post a Comment
Leave Comment