1

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.

andrsnn
  • 1,591
  • 5
  • 25
  • 43
  • 1
    Do you mean `numElementsInX` is the number of elements there *would* be if in `x` if there were no duplicates? – Dave L. Jul 22 '13 at 19:10
  • Edit: sorry it is a global counter. No it is the number of entered values in the array. The user can enter up to 100 values. returning array.length gives the entire initialized array, rather then just the values entered correct? – andrsnn Jul 22 '13 at 19:12

5 Answers5

7

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.

Andy Thomas
  • 84,978
  • 11
  • 107
  • 151
4

this should do it.

public boolean containsDuplicates(Integer[] x) {
   return new HashSet<Integer>(Arrays.asList(x)).size() != x.length
}

You dont need numElementsInX as this is the same as x.length

edit after comment from Louis. Arrays.asList does not work with int arrays.

To convert int[] to Integer try this question How to convert int[] to Integer[] in Java?

or do soemthing like this (not tested but from memory)

Integer[] newArray = new Integer[a.length];
System.arraycopy(a, 0, newArray, 0, a.length);
Community
  • 1
  • 1
RNJ
  • 15,272
  • 18
  • 86
  • 131
  • 1
    Will that compare, ONLY the amount of values entered rather then the entire initialized length of the array. Hence the counter? Its beyond me but ill try piecing it apart thanks! – andrsnn Jul 22 '13 at 19:10
  • Start by understanding that `Set`s do not allow duplicate elements and go from there. – roippi Jul 22 '13 at 19:11
  • 1
    -1. `Arrays.asList` does not work like you expect it to for an `int[]`. This doesn't actually work. – Louis Wasserman Jul 22 '13 at 19:13
  • I am just confused as my professor told me array.length will return the entire initialized array of 100 rather then solely what the user enters. Ill post how I am prompting for the array data. – andrsnn Jul 22 '13 at 19:15
  • @user2210274 If you want to query the amount of values you've set yourself, use and increment your own counter every time you add a value. Or better yet, use an implementation of `List`. – Sotirios Delimanolis Jul 22 '13 at 19:16
  • Still buggy - you can't copy an int[] to Integer[] with System.arrayCopy(). And there's still no use of the OP's numElementsInX . I added an answer that works. – Andy Thomas Jul 22 '13 at 20:07
2

This certainly isn't the most efficient way, but since you don't know about Sets yet, you can use two loops:

public static boolean duplicates (int [] x){
    for (int i=0; i<numElementsInX; i++){
        for (int j=i+1; j<numElementsInX; j++){
            if (x[j]==x[i]) return true;
        }
    }
    return false;
}
Anindya Guha
  • 150
  • 1
  • 1
  • 8
1

"set.add()" returns true if the element is not already present in the set and false otherwise. We could make use of that and get rid of "set.contains()" as in the above solution.

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

For java, return true if the array contains a duplicate value,


boolean containsDuplicates(int[] a) {
    
    HashSet<Integer> hs = new HashSet<>();
    
    for(int i = 0; i<a.length; i++) {
        if(!hs.add(a[i])){
            return true;
        }  
    }   
    return false;
}