Type safe Collection checkedCollection()

Type safe Collection checkedCollection()

JDK 1.5 adds a feature called generics to JDK 1.2 collection classes. With generics, it is possible to add only one type of data to a data structure. But the legacy classes, introduced with JDK 1.0, like Vector or Hashtable do not have this opportunity. To overcome this, the Collections class comes with checkedCollection() method that returns another collection object that works like generics, capable to store only one type of data. On this checked collection object, if an element with different data type is added, the JVM throws ClassCastException

Following is the method signature

  • static Collection checkedCollection(Collection col1, Class obj1): Returns a generics version of Collection col1 that can store only elements of type obj1. But still col1 is not modified and non-generics.

checkedSet(), checkedSortedSet(), checkedList() and checkedMap() methods also exist to get a checked version of Set, List and Map classes; introduced with JDK 1.5.

Following program on Type safe Collection checkedCollection() explains how to use the above method.

Type safe Collection checkedCollection()
Output screenshot on Type safe Collection checkedCollection()

List firstList = new ArrayList();
firstList.add(10);

An object of ArrayList firstList is created and added with a few integer elements with add() method.

List secondList = Collections.checkedList(firstList, Integer.class);
System.out.println(“secondList elements: ” + secondList);

The checkedList(firstList, Integer.class) returns an object List, secondList, containing the same elements of firstList. The secondList object accepts only integers.

firstList.add(“hello”);

As firstList is not generics, it accepts also a string element.

// secondList.add(“hello”);

The above statement raises ClassCastException as secondList does not accept strings; accepts only integer values.

Set firstSet = new HashSet();
firstSet.add(“hello”); firstSet.add(“world”);

A Set object firstSet is created and added only string elements.

Set secondSet = Collections.checkedSet(firstSet, String.class);

The secondSet object returned by the checkedSet() method accepts only String values.

// secondSet.add(10);

The above statement throws ClassCastException at runtime as secondList is added with an integer value where secondList is designed to accept only string values.

One thought on “Type safe Collection checkedCollection()

Leave a Reply

Your email address will not be published. Required fields are marked *