Reputation: 105
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
Reputation: 62884
You can use a Set
, which doesn't allow duplicates.
Set
.Set
with the size of the array.
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
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
Reputation: 93892
Pre-java 8, you could use a Set
as @kocko said (+1 to him). If you don't mind using java-8, here's a one-liner:
public static boolean hasDistinctElements(int[] array) {
return IntStream.of(array).distinct().count() == array.length;
}
Upvotes: 5
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