5:17 pm - Monday April 24, 2017

The Collection Program Singleton used to return an immutable list containing only the specified object using SingletonList(T o) method

CANDID INDUSTRIAL TRAINING -- CHENNAI
Corporate Training for Experienced Candidate
Struts | Hibernate | Spring | Java / J2EE
SOAP | RestFull | Design Pattern | more...
Ph: +91 72000 69003
137b, 2nd st, shanthi nagar, Chrompet, Chennai -600044

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

Filed in: Z-A All Java Codes

Comments are closed.