Search whether any object in 'objects' array does equal 'another object'. - Java Collection Framework

Java examples for Collection Framework:Array Search

Description

Search whether any object in 'objects' array does equal 'another object'.

Demo Code

/*******************************************************************************
 * Copyright (c) 2010 SAP AG.//w  w  w  . j  a  v  a2  s.c o m
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Emil Simeonov - initial API and implementation.
 *    Dimitar Donchev - initial API and implementation.
 *    Dimitar Tenev - initial API and implementation.
 *    Nevena Manova - initial API and implementation.
 *    Georgi Konstantinov - initial API and implementation.
 *    Jakob Spies - initial API and implementation.
 *******************************************************************************/
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;

public class Main{
    public static void main(String[] argv){
        Object objects = "java2s.com";
        Object searchForObject = "java2s.com";
        System.out.println(containsObject(objects,searchForObject));
    }
    /**
     * Search whether any object in 'objects' array does equal 'searchForObject'.
     * @param objects can be null, and can contain null values
     * @param searchForObject can be null
     * @return true if searchForObject is found in 'objects'
     */
    public static boolean containsObject(Object objects[],
            Object searchForObject) {
        if (objects == null) {
            return false;
        }
        for (Object object : objects) {
            boolean found = object == null ? searchForObject == null
                    : object.equals(searchForObject);
            if (found) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials