Java, Return true if array contains duplicate values

andrsnn picture andrsnn · Jul 22, 2013 · Viewed 18k times · Source

I am trying to have a method (duplicates) return true if a given array called x (entered by user in another method), contains duplicate values. Otherwise it would return false. Rather then checking the entire array, which is initialized to 100, it will check only the amount of values entered, which is kept track of with a global counter: numElementsInX.

What is the best way to accomplish this?

public static boolean duplicates (int [] x)

I am prompting for user data like so:

public static void readData (int [] x, int i){

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter integers, enter -999 to stop");

    while (i <= 99) {
        int temp = input.nextInt();
            if(temp == -999){
                break;
            }
            else {
                x[i++]=temp;
            }

    // else

}//end while
        printArray(x,i);


}//end readData

public static void printArray(int [] x, int numElementsInX){

int n = numElementsInX;

for (int i = 0; i < n; i++){
    System.out.print(x[i] + " ");


}//end for
        System.out.println();
}//end printArray

I am sure there is a better way to do this, but this is how I have been taught so far.

Answer

Andy Thomas picture Andy Thomas · Jul 22, 2013

Here is a solution that:

  • Compiles and executes without throwing.
  • Uses numElementsInX as you requested.
  • Returns as soon as it finds a duplicate.

This approach tests whether each member of the array has been seen before. If it has, the method can return immediately. If it hasn't, then the member is added to the set seen before.

public static boolean duplicates (int [] x, int numElementsInX ) {
    Set<Integer> set = new HashSet<Integer>();
    for ( int i = 0; i < numElementsInX; ++i ) {
        if ( set.contains( x[i])) {
            return true;
        }
        else {
            set.add(x[i]);
        }
    }
    return false;
}

Here's a sample program containing the above code.