Junior — Middle
What is the purpose of the Set interface in Java?
sobes.tech AI
Answer from AI
The Set interface in Java represents a collection that does not allow duplicate elements. Its main purpose is to store unique objects without a specific order (unless using specific implementations with ordering).
Key features of Set:
- Contains no duplicate elements.
- Allows quick checking for the presence of an element.
Example usage:
Set<String> set = new HashSet<>();
set.add("apple");
set.add("banana");
set.add("apple"); // will not be added again, as "apple" already exists
System.out.println(set.size()); // Outputs 2
Set is useful when you need to guarantee data uniqueness, for example, when collecting unique identifiers or filtering out duplicate values.