Java examples for java.util:Collection Element
Ensures that all elements of the given collection can be cast to a desired type.
//package com.java2s; import java.util.Collection; public class Main { public static void main(String[] argv) { Collection collection = java.util.Arrays.asList("asdf", "java2s.com"); Class type = String.class; System.out.println(checkCollection(collection, type)); }/*from www .j a va 2 s.c om*/ /** Indicates whether collection elements should be actually checked. */ private static final boolean DEBUG = true; /** * Ensures that all elements of the given collection can be cast to a * desired type. * * @param collection * the collection to check * @param type * the desired type * @return a collection of the desired type * @throws ClassCastException * if an element cannot be cast to the desired type */ @SuppressWarnings("unchecked") public static <E> Collection<E> checkCollection( Collection<?> collection, Class<E> type) { if (DEBUG) { for (Object element : collection) { type.cast(element); } } return (Collection<E>) collection; } }