The singleton() method in Java is a utility method provided by the java.util.Collections class. It returns an immutable set containing only a single, specified object. This method is useful when you need to create a set with exactly one element, providing a convenient and efficient way to represent singletons in your application.
Table of Contents
- Introduction
singleton()Method Syntax- Examples
- Basic Usage of
singleton() - Using
singleton()with Custom Classes
- Basic Usage of
- Real-World Use Case
- Conclusion
Introduction
The Collections.singleton() method is designed to create a set that contains exactly one element. The returned set is immutable, meaning that it cannot be modified after creation. This is useful for scenarios where you need to pass a single element as a set or when you need to enforce a single-element collection in your logic.
The singleton set ensures that the specified element is the only one present, and any attempt to modify the set will result in an UnsupportedOperationException.
singleton() Method Syntax
The syntax for the singleton() method is as follows:
public static <T> Set<T> singleton(T o)
Parameters:
o: The single element to be stored in the returned set.
Returns:
- An immutable set containing only the specified object.
Throws:
NullPointerExceptionif the specified object is null.
Examples
Basic Usage of singleton()
The following example demonstrates how to use the singleton() method to create a set containing a single string.
Example
import java.util.Collections;
import java.util.Set;
public class SingletonExample {
public static void main(String[] args) {
// Create a singleton set containing a single element "Hello"
Set<String> singletonSet = Collections.singleton("Hello");
// Display the singleton set
System.out.println("Singleton Set: " + singletonSet);
// Attempt to modify the singleton set (will throw UnsupportedOperationException)
try {
singletonSet.add("World");
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton set");
}
}
}
Output:
Singleton Set: [Hello]
Error: Cannot modify an immutable singleton set
Using singleton() with Custom Classes
You can also use the singleton() method to create a set containing a single instance of a custom class.
Example
import java.util.Collections;
import java.util.Set;
class Student {
String name;
Student(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class CustomSingletonExample {
public static void main(String[] args) {
// Create a Student object
Student student = new Student("Amit");
// Create a singleton set containing the Student object
Set<Student> singletonStudentSet = Collections.singleton(student);
// Display the singleton student set
System.out.println("Singleton Student Set: " + singletonStudentSet);
// Attempt to modify the singleton student set (will throw UnsupportedOperationException)
try {
singletonStudentSet.add(new Student("Neha"));
} catch (UnsupportedOperationException e) {
System.out.println("Error: Cannot modify an immutable singleton student set");
}
}
}
Output:
Singleton Student Set: [Amit]
Error: Cannot modify an immutable singleton student set
Explanation:
-
Single Element: The
singleton()method creates a set containing only the specified single element, ensuring immutability. -
Immutable Nature: Any attempt to modify the singleton set results in an
UnsupportedOperationException, demonstrating the immutability of the set. -
Custom Class: The method works with custom class instances, allowing you to create single-element sets with user-defined objects.
Real-World Use Case
Returning a Single Element Set from a Method
In real-world applications, the singleton() method can be used to return a single-element set from a method, simplifying code that requires a set but only needs to handle one element.
Example
Imagine a scenario where you need to return a set of permissions for a user, and the user has only one specific permission.
import java.util.Collections;
import java.util.Set;
class Permission {
String name;
Permission(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
public class PermissionExample {
public static void main(String[] args) {
// Get a set of permissions for a user
Set<Permission> userPermissions = getUserPermissions("admin");
// Display the user's permissions
System.out.println("User Permissions: " + userPermissions);
}
// Method to return a singleton set of permissions based on user role
public static Set<Permission> getUserPermissions(String role) {
if ("admin".equals(role)) {
return Collections.singleton(new Permission("FULL_ACCESS"));
} else {
return Collections.singleton(new Permission("READ_ONLY"));
}
}
}
Output:
User Permissions: [FULL_ACCESS]
Explanation:
-
Permission Logic: The
getUserPermissions()method returns a singleton set based on the user’s role, ensuring that each role has a specific, immutable permission set. -
Single Element Set: The singleton set simplifies the handling of permissions by enforcing a single-element collection, reducing complexity and improving code clarity.
Conclusion
The Collections.singleton() method is a powerful utility for creating immutable sets containing a single element in Java. By providing a simple way to represent single-element collections, it enhances the flexibility and readability of your code. This method is particularly valuable in scenarios where you need to enforce single-element collections, improving the robustness and maintainability of your Java applications.