Collections.checkedCollection in Java

By Arvind Rai, February 04, 2022
Find the Java doc of Collections.checkedCollection method.
static <E> Collection<E> checkedCollection(Collection<E> c, Class<E> type) 
1. The 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

The checkedCollection is used as following.
Collection<String> items =  Collections.checkedCollection(new ArrayList<>(), String.class);
items.add("Item1");
items.add("Item2");
System.out.println(items); 
Output
[Item1, Item2] 
Type safe view is also created using generic mechanism.
Collection<String> items = new ArrayList<>(); 
But this will fail if we pass this collection to third party library which does not follow generic mechanism.

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);
  }
} 
Output
[Item1, 10, Item2] 
To get rid of such scenarios, we can use 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);
  }
} 
In the above case we will get exception because integer data is added in string type collection.
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) 

Reference

Java Collections
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us