Java Reference
In-Depth Information
<K,V> Map<K,V> checkedMap(Map<K,V> m, Class<K> keyType, Class<V> valueType)
<K,V> NavigableMap<K,V> checkedNavigableMap(NavigableMap<K,V> m, Class<K>
keyType, Class<V> valueType)
<E> NavigableSet<E> checkedNavigableSet(NavigableSet<E> s, Class<E> type)
<E> Queue<E> checkedQueue(Queue<E> queue, Class<E> type)
<E> Set<E> checkedSet(Set<E> s, Class<E> type)
<K,V> SortedMap<K,V> checkedSortedMap(SortedMap<K,V> m, Class<K> keyType,
Class<V> valueType)
<E> SortedSet<E> checkedSortedSet(SortedSet<E> s, Class<E> type)
Here is the solution of the previous example that will throw a ClassCastException when an attempt is made to
add an Integer to the Set of String :
// Work with a checked Set of String type
Set<String> checkedSet = Collections.checkedSet(new HashSet<String>(), String.class);
Set anythingGoesSet = checkedSet;
anythingGoesSet.add(new Integer(123)); // Throws ClassCastException
Using a checked collection does not stop you from bypassing the compiler. rather, it helps you identify the
offending code easily and exactly at runtime.
Tip
Creating Empty Collections
Sometimes you need to call a method that accepts a collection. However, you do not have any elements for the
collection to pass. In such cases, you do not need to go through the hassle of creating a collection object. The
Collections class provides an immutable empty collection object of each type as a return value of its static methods.
It also provides methods that return an empty Iterator . The following is a list of such static methods in the
Collections class:
<T> List<T> emptyList()
<K,V> Map<K,V> emptyMap()
<T> Set<T> emptySet()
<T> Iterator<T> emptyIterator()
<T> ListIterator<T> emptyListIterator()
Using these methods is straightforward. Suppose there is a method called m1(Map<String,String> map) . If you
want to pass an empty map to this method, your call would be m1(Collections.emptyMap()) .
 
 
Search WWH ::




Custom Search