Check whether the given Collection contains the given element instance. - Java java.util

Java examples for java.util:Collection Contain

Description

Check whether the given Collection contains the given element instance.

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");
        Object element = "java2s.com";
        System.out.println(containsInstance(collection, element));
    }/*  www . j a  va2 s .  c o m*/

    /**
     * Check whether the given Collection contains the given element instance.
     * <p>
     * Enforces the given instance to be present, rather than returning
     * <code>true</code> for an equal element as well.
     * 
     * @param collection
     *            the Collection to check
     * @param element
     *            the element to look for
     * @return <code>true</code> if found, <code>false</code> else
     */
    public static boolean containsInstance(Collection<?> collection,
            Object element) {
        if (collection != null) {
            for (Object candidate : collection) {
                if (candidate == element) {
                    return true;
                }
            }
        }
        return false;
    }
}

Related Tutorials