Ensures that all elements of the given list can be cast to a desired type. - Java java.util

Java examples for java.util:List Element

Description

Ensures that all elements of the given list can be cast to a desired type.

Demo Code


//package com.java2s;

import java.util.List;

public class Main {
    public static void main(String[] argv) {
        List list = java.util.Arrays.asList("asdf", "java2s.com");
        Class type = String.class;
        System.out.println(checkList(list, type));
    }/*from  w w  w  .j  a  v a  2s. c o m*/

    /** Indicates whether collection elements should be actually checked. */
    private static final boolean DEBUG = true;

    /**
     * Ensures that all elements of the given list can be cast to a desired
     * type.
     * 
     * @param list
     *            the list to check
     * @param type
     *            the desired type
     * @return a list of the desired type
     * @throws ClassCastException
     *             if an element cannot be cast to the desired type
     */
    @SuppressWarnings("unchecked")
    public static <E> List<E> checkList(List<?> list, Class<E> type) {
        if (DEBUG) {
            for (Object element : list) {
                type.cast(element);
            }
        }
        return (List<E>) list;
    }
}

Related Tutorials