Cast objects to clazz - Java java.util

Java examples for java.util:Collection Element

Description

Cast objects to clazz

Demo Code


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

public class Main{
    public static void main(String[] argv){
        Collection objects = java.util.Arrays.asList("asdf","java2s.com");
        System.out.println(castAll(objects));
    }/*from  w w w . j  a va  2  s  . c  o m*/
    /**
     * Cast objects to clazz
     */
    @SuppressWarnings("unchecked")
    public static <A> List<A> castAll(Collection<?> objects) {
        List<A> results = new ArrayList<A>(objects.size());
        for (Object object : objects) {
            results.add((A) object);
        }
        return results;
    }
    /**
     * Unchecked cast objects to clazz; CastClassException will occur when object sent in does not match clazz<br>
     * <br>
     * Use when all objects are expected to be of type class and exception is desired if not
     */
    public static <A extends Object> List<A> castAll(Class<A> clazz,
            Collection<? extends Object> objects) {
        return cast(clazz, objects, CastOption.ALL);
    }
    /**
     * Cast objects to clazz
     * 
     * @param castOption if ALL, cast all and throw exception if cast fails; if MATCHING, only cast those of type clazz
     */
    @SuppressWarnings("unchecked")
    private static <A extends Object> List<A> cast(Class<A> clazz,
            Collection<? extends Object> objects, CastOption castOption) {
        List<A> results = new ArrayList<A>(objects.size());
        for (Object object : objects) {
            if ((castOption == CastOption.ALL)
                    || ((castOption == CastOption.MATCHING) && (object
                            .getClass().isAssignableFrom(clazz)))) {
                results.add((A) object);
            }
        }
        return results;
    }
}

Related Tutorials