The following nine static methods of the class Collections convert the provided collection from a raw type (one without generics) to a certain type of element. The name checked implies that after the transformation, the type of each newly added element will be checked:
- Set<E> checkedSet(Set<E> s, Class<E> type)
- List<E> checkedList(List<E> list, Class<E> type)
- Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
- Collection<E> checkedCollection(Collection<E> collection, Class<E> type)
- Map<K,V> checkedMap(Map<K,V> map, Class<K> keyType, Class<V> valueType)
- SortedSet<E> checkedSortedSet(SortedSet<E> set, Class<E> type)
- NavigableSet<E> checkedNavigableSet(NavigableSet<E> set, Class<E> type)
- SortedMap<K,V> checkedSortedMap(SortedMap<K,V> map, Class<K> keyType, Class<V> valueType)
- NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> map, Class<K> keyType, Class<V> valueType)
Here is the demonstration code:
List list = new ArrayList();
list.add("s1");
list.add("s2");
list.add(42);
System.out.println(list); //prints: [s1, s2, 42]
List cList = Collections.checkedList(list, String.class);
System.out.println(list); //prints: [s1, s2, 42]
list.add(42);
System.out.println(list); //prints: [s1, s2, 42, 42]
//cList.add(42); //throws ClassCastException
You can observe that conversion does not affect the current elements of the collection. We have added objects of the String class and an object of the Integer class to the same list and were able to convert it to a checked list cList without any problem. We can continue adding to the original list objects of different types, but the attempt to add a non-String object to the checked list generates ClassCastException at runtime.