Collections.checkedCollection in Java
February 04, 2022
Find the Java doc of Collections.checkedCollection
method.
static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type)
checkedCollection
returns a dynamically typesafe view of the specified collection.
2. Any attempt to insert an element of the wrong type will result in an immediate
ClassCastException
.
3. The collection returned by
checkedCollection
guarantees that the collection cannot contain an incorrectly typed element.
4. Generic mechanism alone cannot guarantee type checking, because it is compile-time type checking. Generic mechanism will fail when we pass our collection to third party library of older version which does not follow type checking.
Example-1
ThecheckedCollection
is used as following.
Collection<String> items = Collections.checkedCollection(new ArrayList<>(), String.class); items.add("Item1"); items.add("Item2"); System.out.println(items);
[Item1, Item2]
Collection<String> items = new ArrayList<>();
Example-2
In this example we will show that a generic collection will fail to keep type safe and we will not get any error.For this, create a generic collection and pass to a method that is not type safe.
CheckedCollection2.java
package com.concretepage; import java.util.ArrayList; import java.util.Collection; public class CheckedCollection2 { public static void main(String[] args) { Collection<String> items = new ArrayList<>(); items.add("Item1"); CheckedCollection2.thirdPartyMethod(items); items.add("Item2"); System.out.println(items); } public static void thirdPartyMethod(Collection list) { list.add(10); } }
[Item1, 10, Item2]
Collections.checkedCollection
method.
CheckedCollection3.java
package com.concretepage; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; public class CheckedCollection3 { public static void main(String[] args) { Collection<String> items = Collections.checkedCollection(new ArrayList<>(), String.class); items.add("Item1"); CheckedCollection3.thirdPartyMethod(items); items.add("Item2"); System.out.println(items); } public static void thirdPartyMethod(Collection list) { list.add(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.base/java.util.Collections$CheckedCollection.typeCheck(Collections.java:3097)