Javatpoint Logo
Javatpoint Logo

Java Collections singleton() Method

The singleton() method of Java Collections class is used to get an immutable set which contains only the specified object.

Syntax

Following is the declaration of singleton() method:

Parameter

Parameter Description Required/Optional
o It is the object which will be stored in the returned set. Required

Returns

The singleton() method returns an immutable set which contains only the specified object.

Exceptions

NA

Compatibility Version

Java 1.3 and above

Example 1

Test it Now

Output:

[1, 2, 4, 2, 7, 2, 4, 4]
[1, 2, 4, 2, 7, 2, 4]
[1, 2, 2, 7, 2]

Example 2

Test it Now

Output:

[A, B, C, A, C, D, C]
[A, C, A, C, D, C]
[A, A, D]

Example 3

Test it Now

Output:

Enter the value: A
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.CollectionsSingletonExample3.main(CollectionsSingletonExample3.java:7)





Please Share

facebook twitter google plus pinterest

Learn Latest Tutorials


Preparation


B.Tech / MCA