Java Array Duplicate hasDuplicates(final T[] array)

Here you can find the source of hasDuplicates(final T[] array)

Description

Determines whether a given array contains duplicate values.

License

Open Source License

Parameter

Parameter Description
T The type of the array elements.
array An array.

Exception

Parameter Description
IllegalArgumentException if array is null.

Return

true iff the given array contains duplicate values.

Declaration

public static <T> boolean hasDuplicates(final T[] array) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.util.List;

public class Main {
    /**//  w  ww.  j a  v  a 2 s.c o m
     * Determines whether a given collection contains duplicate values.
     *
     * @param <T> The type of the collection elements.
     * @param elements    A collection.
     *
     * @return true if the given collection contains duplicate values.
     */
    public static <T> boolean hasDuplicates(final List<T> elements) {
        int n = elements.size();
        for (int i = 0; i < n - 1; i++) {
            final T e1 = elements.get(i);
            for (int j = i + 1; j < n; j++) {
                final T e2 = elements.get(j);
                if (areEqual(e1, e2))
                    return true;
            }
        }
        return false;
    }

    /**
     * Determines whether a given array contains duplicate values.
     *
     * @param <T>   The type of the array elements.
     * @param array An array.
     *
     * @return true iff the given array contains duplicate values.
     *
     * @throws IllegalArgumentException if {@code array} is {@code null}.
     */
    public static <T> boolean hasDuplicates(final T[] array) {
        if (array == null) {
            throw new IllegalArgumentException();
        }
        for (int i = 0; i < array.length - 1; i++) {
            final T x = array[i];
            for (int j = i + 1; j < array.length; j++) {
                final T y = array[j];
                if (x.equals(y)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * Returns true if the given objects are equal, namely, they are both null or they are equal by the {@code equals()} method.
     *
     * @param x the first compared object.
     * @param y the second compared object.
     *
     * @return true if the given objects are equal.
     */
    public static boolean areEqual(final Object x, final Object y) {
        return x == null ? y == null : x.equals(y);
    }
}

Related

  1. addNoDuplicate(String[] array, String target)
  2. arrayDuplicate(byte[] in)
  3. deleteDuplicatedPages(int[] pages)
  4. duplicateArrayEntries(String[] inputArr, int numDuplicates)
  5. eraseDuplicatedValue(String[] srcArr)
  6. isDuplicated(String[] strArray)
  7. removeDuplicates(double[] array)
  8. removeDuplicates(final Object[] array)
  9. removeDuplicates(int[] input)