Unique Algorithm in Java

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 site contains affiliate links. If you click an affiliate link and make a purchase we may get a small commission. It doesn't affect the price you pay, but it is something we must disclose.