Reputation: 11
For example,I have an 1-D array ,how can I check if all the elements are different?(no one same with other,all of them should be different) Use for-loop?Or something else?
I thought maybe this,but cannot be true:
int []array={1,2,3,4,4,6}
for(int i=0;i<a.length;i++){
if(a[i]!=a[i+1])
return true;
else
return false;
}
so is there some good method can use to check different?
Upvotes: 0
Views: 101
Reputation: 2100
Set<String> values = new HashSet<>(Arrays.asList(array));
assertEquals(array.length, values.size());
Upvotes: 0
Reputation: 5308
There are several ways to do this. For example, you can use two for
loops:
boolean hasDuplicates(int[] array) {
for (int i = 0; i < array.length; i++) {
for (int j = i + 1; j < array.length; j++) {
if (array[i] == array[j]) {
return true;
}
}
}
return false;
}
If that’s too much writing for you, you can just create a Set
from the array and compare the size of the set and the array. The set automatically drops duplicate entries.
Upvotes: 0
Reputation: 178263
Create a HashSet
(or another kind of Set
), and loop through the elements of your array. Add them one at a time. If the element already exists in the Set
, then not all are different and you can return false
. You can tell this if add
returns false
; then you don't have to check the rest of the array. If you finish with the entire array and none are the same, then they're all different and you can return true
.
The problem with your current code is that you only check the first and second elements, and you return something right away based on that comparison, and you don't consider the rest of the elements.
Upvotes: 2
Reputation: 71
Add all items from the array into a Set and check the set size with the original array size.
If they're different sizes, then there's a duplicate element.
Upvotes: 7