Need to check whether all values in a Java array are unique? Here you go.
public boolean unique(int[] ray) {
for (int i = 0; i < ray.length; i++) {
for (int j = i + 1; j < ray.length; j++) {
if (ray[i] == ray[j]) {
return false;
}
}
}
return true;
}
This isn’t a super efficient solution, but it does work.
What we’re doing is starting at the first element in the array. From there we start a nested loop starting at the next element and look at every element from that point. If there’s a match, then the method returns false
because a match means that all elements aren’t unique. If we get to the end of the loop and there’s no match, then we return true
.
This post is part of a series of algorithms used in array manipulation