Monday 6 July 2015

Java : Collection Framework : Collections (nCopies)


Click here to watch in Youtube :
https://www.youtube.com/watch?v=TJ0VUHRfyuw&list=UUhwKlOVR041tngjerWxVccw

CollectionsExample.java
import java.util.Collections;
import java.util.List;

/*
 Method: 

 public static <T> List<T> nCopies(int n,T o)

 Parameters:

 n - the number of elements in the returned list.
 o - the element to appear repeatedly in the returned list.

 Returns:

 an immutable list consisting of n copies of the specified object.

 */

public class CollectionsExample
{

    public static void main(String[] args)
    {

        /*
         * Returns an immutable list consisting of n copies of the specified
         * object.
         */
        List<String> list = Collections.nCopies(5, "Ram");

        System.out.println("list : " + list);
        
        /*We cann't add elements in the Immutable List */
        
        list.add("Peter");

    }

}
Output
list : [Ram, Ram, Ram, Ram, Ram]
Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.AbstractList.add(AbstractList.java:148)
    at java.util.AbstractList.add(AbstractList.java:108)
    at CollectionsExample.main(CollectionsExample.java:36)
To Download CollectionsDemo-nCopies Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/CollectionsDemo-nCopies.zip?attredirects=0&d=1

See also:
  • All JavaEE Viedos Playlist
  • All JavaEE Viedos
  • All JAVA EE Links
  • Servlets Tutorial
  • All Design Patterns Links
  • JDBC Tutorial
  • Java Collection Framework Tutorial
  • JAVA Tutorial
  • No comments:

    Post a Comment