Collections singletonList() method in Java with Examples
The singletonList()
method is a static method of the java.util.Collections
class in Java. It returns an immutable list containing only the specified object. The returned list is serializable.
Syntax:
public static <T> List<T> singletonList(T obj)
Parameters: - obj: the object to be stored in the list.
Return Value: - an immutable list containing only the specified object.
Example 1: Using singletonList() method to create a list of a single element
import java.util.Collections;
import java.util.List;
public class SingletonListExample {
public static void main(String[] args) {
String str = "Hello";
List<String> list = Collections.singletonList(str);
System.out.println(list); // Output: [Hello]
}
}
Example 2: Trying to modify the returned list throws UnsupportedOperationException
import java.util.Collections;
import java.util.List;
public class SingletonListExample {
public static void main(String[] args) {
String str = "Hello";
List<String> list = Collections.singletonList(str);
list.add("World"); // Throws UnsupportedOperationException
}
}
Example 3: Using singletonList() method to create a list of a single element of a custom class
import java.util.Collections;
import java.util.List;
public class SingletonListExample {
public static void main(String[] args) {
Person person = new Person("John", 30);
List<Person> list = Collections.singletonList(person);
System.out.println(list); // Output: [Person{name='John', age=30}]
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}