check Content of a Collection by instanceof operator - Java java.util

Java examples for java.util:Collection Operation

Description

check Content of a Collection by instanceof operator

Demo Code


//package com.java2s;
import java.util.Collection;

public class Main {
    public static void main(String[] argv) {
        Collection collection = java.util.Arrays.asList("asdf",
                "java2s.com");
        Class clazz = String.class;
        checkContent(collection, clazz);
    }// w  ww.  j a v  a2s. c  om

    public static void checkContent(final Collection<?> collection,
            final Class<?> clazz) {
        for (final Object o : collection) {
            if (!clazz.isInstance(o)) {
                throw new IllegalArgumentException(
                        "Collection has an instance of " + o.getClass()
                                + ", which doesn't inherit from " + clazz);
            }
        }
    }
}

Related Tutorials