Java Array Contain arrayContains(Object[] array, Object element)

Here you can find the source of arrayContains(Object[] array, Object element)

Description

Check if an unsorted array contains an element.

License

Open Source License

Parameter

Parameter Description
array a parameter
element a parameter

Declaration

public static boolean arrayContains(Object[] array, Object element) 

Method Source Code

//package com.java2s;
/**/*from w w  w.j av a2s . c  o  m*/
 * Copyright (C) 2015 WING, NUS and NUS NLP Group.
 * 
 * This program is free software: you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License along with this program. If
 * not, see http://www.gnu.org/licenses/.
 */

import java.util.Arrays;

public class Main {
    /**
     * Check if an <b>unsorted</b> array contains an element.
     * <p>
     * Complexity <i>O(n)</i>.
     * 
     * @param array
     * @param element
     * @return
     */
    public static boolean arrayContains(Object[] array, Object element) {
        return arrayContains(array, element, false);
    }

    /**
     * Check if any type of array contains an element.
     * 
     * <ul>
     * Complexity:
     * <li>for unsorted array: <i>O(n)</i>
     * <li>for sorted array: <i>O(log(n))</i>
     * 
     * <p>
     * 
     * @param array
     * @param element
     * @param isSorted
     * @return true if the array contains an element that returns {@code true}
     *         for the {@code element} when calling {@code equals}
     */
    public static boolean arrayContains(Object[] array, Object element, boolean isSorted) {

        if (isSorted) {
            return Arrays.binarySearch(array, element) >= 0;
        } else {
            for (int i = 0; i < array.length; ++i) {
                if (array[i].equals(element)) {
                    return true;
                }
            }
            return false;
        }
    }
}

Related

  1. arrayContains(int[] array, int value)
  2. arrayContains(Object obj, Object[] array)
  3. arrayContains(Object[] a, Object ob)
  4. arrayContains(Object[] array, Object el)
  5. arrayContains(Object[] array, Object el)
  6. ArrayContains(Object[] array, Object obj)
  7. arrayContains(Object[] array, Object object)
  8. arrayContains(Object[] element, Object[][] array)
  9. arrayContains(Object[] haystack, Object needle)