96
Java Collections singletonList() Method
The singletonList() method of Java Collections class is used to get an immutable list which contains only the specified object.
Syntax
Following is the declaration of singletonList() method:
Parameter
Parameter | Description | Required/Optional |
---|---|---|
o | It is the object which will be stored in the returned List. | Required |
Returns
The singletonList() method returns an immutable List which contains only the specified object.
Exceptions
NA
Compatibility Version
Java 1.3 and above
Example 1
Output:
Number List elements: [10] String List elements: [Hello India]
Example 2
Output:
List value before: [One, Two, Three, One, Two, Three, TutorAspire ] List value after: [One]
Example 3
Output:
1.Enter the value: 55 Output: [55] 2.Enter the value: Java Exception in thread "main" java.util.InputMismatchException at java.base/java.util.Scanner.throwFor(Scanner.java:939) at java.base/java.util.Scanner.next(Scanner.java:1594) at java.base/java.util.Scanner.nextInt(Scanner.java:2258) at java.base/java.util.Scanner.nextInt(Scanner.java:2212) at myPackage.CollectionsSingletonListExample3.main(CollectionsSingletonListExample3.java:7)
Next TopicJava Collections Class