Samkough
Samkough

Reputation: 105

Checking whether you have two of the same elements in one integer array

How can you check (in Java) if you have two or more of the same elements in an integer array?

An example is if you want to get the mode of an array and the array might not have two or more of the same elements, so there wouldn't be any mode. In order to know that though, you would have to check whether you have two of the same elements in that array.

Upvotes: 0

Views: 194

Answers (4)

Konstantin Yovkov
Konstantin Yovkov

Reputation: 62884

You can use a Set, which doesn't allow duplicates.

  1. Add all the elements of the array to the Set.
  2. Compare the size of the Set with the size of the array.
    • if they are equal, then there are no duplicates
    • otherwise, there are duplicates.

For example:

int[] array = ...
Set<Integer> set = new HashSet<Integer>();
for (int i : array) {
    set.add(i);
}
if (set.size() == array.length) {
    System.out.println("There are no duplicates");
} else {
    System.out.println("There are duplicates");
}

Upvotes: 3

vefthym
vefthym

Reputation: 7462

You can use the following method, which sorts the array and then checks for duplicates in the neighbors:

private boolean checkDuplicates(int[] array) {
    Arrays.sort(array);                        //sort the array in ascending order
    int prevElem = array[0];
    for (int i = 1; i < array.length; ++i) {
        if (array[i] == prevElem) { //if duplicates exist, they will be neighbors, since the array is sorted
            return true; //no need to examine the rest of the array elements, if a duplicate is found
        }
        prevElem = array[i];
    }
    return false; //if no duplicates are found, return true
}

Upvotes: 1

Alexis C.
Alexis C.

Reputation: 93892

Pre-java 8, you could use a Set as @kocko said (+1 to him). If you don't mind using , here's a one-liner:

public static boolean hasDistinctElements(int[] array) {
    return IntStream.of(array).distinct().count() == array.length;
}

Upvotes: 5

Spikatrix
Spikatrix

Reputation: 20252

One way is by looping,using nested loops.

for(int i=0; i<arr.length ; i++)
    for(int j=i; j<arr.length ; j++)
        if(arr[i] == arr[j])
            //two same elements detected

Upvotes: 1

Related Questions