Java tutorial
//package com.java2s; //it under the terms of the GNU Affero General Public License as published by import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; public class Main { /** * Check the type of list contents (for the situations where a simple upcast * is not enough.) As Java generics are implemented via erasure, * unfortunately the target class has to be passed as a parameter. * <p> * Basically, you can convert a list to a typed list via this method, using: * <pre> * List someList = ...; // from somewhere else * List<MyType> = typecheck(someList, MyType.class); * </pre> * The method will raise a class cast exception, if the input list contains * any element, that is not instanceof MyType or null. * @param T the target type * @param l the input list * @param tClass T's class * @return l as a parameterized type * * @deprecated In the most common use case this is unnecessary. In the second * common use case this is a sign that you have not understood generics. */ public static <T> List<T> typecheck(List<?> l, Class<T> tClass) { if (l == null) return null; for (Object o : l) if (o != null && !tClass.isInstance(o)) throw new ClassCastException("ClassCast from " + o.getClass() + " to " + tClass); return (List<T>) l; } /** * Same as above, but implemented via a new array list instead of a cast. * @param T the target type * @param l the input collection * @param tClass T's class * @return a new array list with all items of l cast into T * * @deprecated In the most common use case this is unnecessary. In the second * common use case this is a sign that you have not understood generics. */ public static <T> List<T> typecheck(Collection<?> l, Class<T> tClass) { if (l == null) return null; ArrayList<T> res = new ArrayList<T>(); for (Object o : l) if (o != null && !tClass.isInstance(o)) throw new ClassCastException("ClassCast from " + o.getClass() + " to " + tClass); else res.add((T) o); return res; } /** * Typecheck as above, performing on map values * @param <K> Key type * @param <V> Designated value type * @param m the map to check * @param vClass the value type's class * @return m, accordingly cast, if no classCastException is thrown * * @deprecated In the most common use case this is unnecessary. In the second * common use case this is a sign that you have not understood generics. */ public static <K, V> Map<K, V> typecheck(Map<K, ?> m, Class<V> vClass) { if (m == null) return null; for (Map.Entry<K, ?> e : m.entrySet()) { Object o = e.getValue(); if (o != null && !vClass.isInstance(o)) throw new ClassCastException("ClassCast from " + o.getClass() + " to " + vClass); } return (Map<K, V>) m; } }