Wednesday 8 July 2015

Java : Collection Framework : Collections (CheckedList)


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

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

/*
 Method: 

 public static <E> List<E> checkedList(List<E> list, Class<E> type)

 Parameters:

 list - the list for which a dynamically typesafe view is to be returned
 type - the type of element that list is permitted to hold

 Returns:

 a dynamically typesafe view of the specified list.
 */

public class CollectionsExample
{

    public static void main(String[] args)
    {

        List myList = new ArrayList();
        myList.add("one");
        myList.add("two");
        myList.add("three");
        myList.add("four");

        System.out.println("myList : " + myList + "\n");
        
        /*
         * Returns a dynamically typesafe view of the specified list.
         */
        List chkList = Collections.checkedList(myList, String.class);

        System.out.println("Checked list : " + chkList + "\n");

        /*
         * you can add any type of elements to myList object.
         */
        myList.add(10);

        System.out.println("myList : " + myList + "\n");

        /*
         * you cannot add any type of elements to chkList object, doing so
         * throws ClassCastException.
         */

        chkList.add(10);
        
        System.out.println("Checked list : " + chkList + "\n");
    }
}
Output
myList : [one, two, three, four]

Checked list : [one, two, three, four]

myList : [one, two, three, four, 10]

Exception in thread "main" java.lang.ClassCastException: Attempt to insert class java.lang.Integer element into collection with element type class java.lang.String
    at java.util.Collections$CheckedCollection.typeCheck(Collections.java:3037)
    at java.util.Collections$CheckedCollection.add(Collections.java:3080)
    at CollectionsExample.main(CollectionsExample.java:53)
Click the below Image to Enlarge

Java : Collection Framework : Collections (CheckedList) 
To Download CollectionsDemoCheckedList Project Click the below link
https://sites.google.com/site/javaee4321/java-collections/CollectionsDemoCheckedList.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