BACK
The singletonList(T) method is used to return an immutable list containing only the specified object.
Example Program
import java.util.*; public class List111 { public static void displayList(List<String> l) { Iterator<String> i = l.iterator(); while (i.hasNext()) System.out.print("\t" + i.next()); System.out.println(); } public static void main(String[] args) { String init[] = { "One", "Two", "Three", "One", "Two", "Three" }; List<String> list = new ArrayList<String>(Arrays.asList(init)); System.out.println("Size of 'List' :" + list.size()); System.out.println("Before Singleton List apply"); System.out.println("Contents of the list 'list':"); displayList(list); System.out.println(); list = Collections.singletonList("four"); System.out.println("After Sigleton List applied "); System.out.println("Contents of the list 'list':"); displayList(list); System.out.println("Size of 'List': " + list.size()); } }
Output:
Size of ‘List’ :6
Before Singleton List apply
Contents of the list ‘list’:
One Two Three One Two Three
After Sigleton List applied
Contents of the list ‘list’:
four
Size of ‘List’: 1
Explanation:
public static <T> List<T> singletonList(T o)
The singletonList(T) method is used to return an immutable list containing only the specified object.
Parameters:
o – the sole object to be stored in the returned set.
Returns:
An immutable set containing only the specified object. The returned list is serializable.
Since:
1.3