Clone the passed list and cast to the new type if the items in the list extend or are an instanceof the passed class. - Android java.util

Android examples for java.util:List Element

Description

Clone the passed list and cast to the new type if the items in the list extend or are an instanceof the passed class.

Demo Code


//package com.java2s;

import java.util.ArrayList;

import java.util.List;

public class Main {
    /**//from ww w.j  a  v a  2 s  .  c o  m
     * Clone the passed list and cast to the new type if the items in the list extend or are an instanceof the passed class.
     *
     * @return the cloned list
     */
    public static <T extends Object, P extends Object> List<P> cloneListAndCast(
            List<T> list, Class<P> clazz) {
        List<P> clone = new ArrayList<>(list.size());
        for (T item : list) {
            if (clazz.isAssignableFrom(item.getClass())) {
                @SuppressWarnings("unchecked")
                P newItem = (P) item;
                clone.add(newItem);
            }
        }
        return clone;
    }
}

Related Tutorials