Here you can find the source of castTo(final List> list, final Class
@SuppressWarnings("unchecked") public static <E> List<E> castTo(final List<?> list, final Class<E> clasz)
//package com.java2s; //License from project: Apache License import java.util.Collection; import java.util.List; public class Main { @SuppressWarnings("unchecked") public static <E> List<E> castTo(final List<?> list, final Class<E> clasz) { if (isOf(list, clasz)) { return (List<E>) list; }//from ww w. j a v a 2 s. c o m throw new IllegalArgumentException("List contains invalid type."); } private static <E> boolean isOf(final Collection<?> collection, final Class<E> clasz) { if (null == collection) { return false; } for (Object o : collection) { if (null != o && !clasz.isInstance(o)) { return false; } } return true; } }