Wednesday, 8 July 2015

Java : Collection Framework : Collections (CheckedList)

Click here to watch in Youtube :
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;


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


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


 a dynamically typesafe view of the specified list.

public class CollectionsExample

    public static void main(String[] args)

        List myList = new ArrayList();

        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.

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

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

        System.out.println("Checked list : " + chkList + "\n");
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(
    at java.util.Collections$CheckedCollection.add(
    at CollectionsExample.main(
Click the below Image to Enlarge

Java : Collection Framework : Collections (CheckedList) 
To Download CollectionsDemoCheckedList Project Click the below link

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

    Google+ Followers

    Google+ Badge